(For more resources related to this topic, see here.)
Using the term method instead of function
You are constantly going to see the words function and method used everywhere as you learn Unity.
The words function and method truly mean the same thing in Unity. They do the same thing.
Since you are studying C#, and C# is an Object-Oriented Programming (OOP) language, I will use the word "method" throughout this article, just to be consistent with C# guidelines. It makes sense to learn the correct terminology for C#. Also, UnityScript and Boo are OOP languages. The authors of the Scripting Reference probably should have used the word method instead of function in all documentation.
From now on I'm going to use the words method or methods in this article. When I refer to the functions shown in the Scripting Reference , I'm going to use the word method instead, just to be consistent throughout this article.
Understanding what a variable does in a script
What is a variable? Technically, it's a tiny section of your computer's memory that will hold any information you put there. While a game runs, it keeps track of where the information is stored, the value kept there, and the type of the value. However, for this article, all you need to know is how a variable works in a script. It's very simple.
What's usually in a mailbox, besides air? Well, usually there's nothing but occasionally there is something in it. Sometimes there's money (a paycheck), bills, a picture from aunt Mabel, a spider, and so on. The point is what's in a mailbox can vary. Therefore, let's call each mailbox a variable instead.
Naming a variable
Using the picture of the country mailboxes, if I asked you to see what is in the mailbox, the first thing you'd ask is which one? If I said in the Smith mailbox, or the brown mailbox, or the round mailbox, you'd know exactly which mailbox to open to retrieve what is inside. Similarly, in scripts, you have to name your variables with a unique name. Then I can ask you what's in the variable named myNumber, or whatever cool name you might use.
A variable name is just a substitute for a value
As you write a script and make a variable, you are simply creating a placeholder or a substitute for the actual information you want to use. Look at the following simple math equation: 2 + 9 = 11
Simple enough. Now try the following equation: 11 + myNumber = ???
There is no answer to this yet. You can't add a number and a word. Going back to the mailbox analogy, write the number 9 on a piece of paper. Put it in the mailbox named myNumber. Now you can solve the equation. What's the value in myNumber? The value is 9. So now the equation looks normal: 11 + 9 = 20
The myNumber variable is nothing more than a named placeholder to store some data (information). So anywhere you would like the number 9 to appear in your script, just write myNumber, and the number 9 will be substituted.
Although this example might seem silly at first, variables can store all kinds of data that is much more complex than a simple number. This is just a simple example to show you how a variable works.
Time for action – creating a variable and seeing how it works
Let's see how this actually works in our script. Don't be concerned about the details of how to write this, just make sure your script is the same as the script shown in the next screenshot.
- In the Unity Project panel, double-click on LearningScript.
- In MonoDevelop, write the lines 6, 11, and 13 from the next screenshot.
- Save the file.
To make this script work, it has to be attached to a GameObject. Currently, in our State Machine project we only have one GameObject, the Main Camera. This will do nicely since this script doesn't affect the Main Camera in any way. The script simply runs by virtue of it being attached to a GameObject.
- Drag LearningScript onto the Main Camera.
- Select Main Camera so that it appears in the Inspector panel.
- Verify whether LearningScript is attached.
- Open the Unity Console panel to view the output of the script.
- Click on Play.
The preceding steps are shown in the following screenshot:
What just happened?
In the following Console panel is the result of our equations. As you can see, the equation on line 13 worked by substituting the number 9 for the myNumber variable:
Time for action – changing the number 9 to a different number
Since myNumber is a variable, the value it stores can vary. If we change what is stored in it, the answer to the equation will change too. Follow the ensuing steps:
- Stop the game and change 9 to 19.
- Notice that when you restart the game, the answer will be 30.
What just happened?
You learned that a variable works by simple process of substitution. There's nothing more to it than that.
We didn't get into the details of the wording used to create myNumber, or the types of variables you can create, but that wasn't the intent. This was just to show you how a variable works. It just holds data so you can use that data elsewhere in your script.
Have a go hero – changing the value of myNumber
In the Inspector panel, try changing the value of myNumber to some other value, even a negative value. Notice the change in answer in the Console.
Using a method in a script
Methods are where the action is and where the tasks are performed. Great, that's really nice to know but what is a method?
What is a method?
When we write a script, we are making lines of code that the computer is going to execute, one line at a time. As we write our code, there will be things we want our game to execute more than once. For example, we can write a code that adds two numbers. Suppose our game needs to add the two numbers together a hundred different times during the game. So you say, "Wow, I have to write the same code a hundred times that adds two numbers together. There has to be a better way."
Let a method take away your typing pain. You just have to write the code to add two numbers once, and then give this chunk of code a name, such as AddTwoNumbers(). Now, every time our game needs to add two numbers, don't write the code over and over, just call the AddTwoNumbers() method.
Time for action – learning how a method works
We're going to edit LearningScript again. In the following screenshot, there are a few lines of code that look strange. We are not going to get into the details of what they mean in this article.Getting into the Details of Methods. Right now, I am just showing you a method's basic structure and how it works:
- In MonoDevelop, select LearningScript for editing.
- Edit the file so that it looks exactly like the following screenshot.
- Save the file.
What's in this script file?
In the previous screenshot, lines 6 and 7 will look familiar to you; they are variables just as you learned in the previous section. There are two of them this time. These variables store the numbers that are going to be added.
Line 16 may look very strange to you. Don't concern yourself right now with how this works. Just know that it's a line of code that lets the script know when the Return/Enter key is pressed. Press the Return/Enter key when you want to add the two numbers together.
Line 17 is where the AddTwoNumbers() method gets called into action. In fact, that's exactly how to describe it. This line of code calls the method.
Lines 20, 21, 22, and 23 make up the AddTwoNumbers() method. Don't be concerned about the code details yet. I just want you to understand how calling a method works.
Method names are substitutes too
You learned that a variable is a substitute for the value it actually contains. Well, a method is no different.
Take a look at line 20 from the previous screenshot:
void AddTwoNumbers ()
The AddTwoNumbers() is the name of the method. Like a variable, AddTwoNumbers() is nothing more than a named placeholder in the memory, but this time it stores some lines of code instead. So anywhere we would like to use the code of this method in our script, just write AddTwoNumbers(), and the code will be substituted.
Line 21 has an opening curly-brace and line 23 has a closing curly-brace. Everything between the two curly-braces is the code that is executed when this method is called in our script.
Look at line 17 from the previous screenshot:
The method name AddTwoNumbers() is called. This means that the code between the curly-braces is executed.
It's like having all of the code of a method right there on line 17.
Of course, this AddTwoNumbers() method only has one line of code to execute, but a method could have many lines of code.
Line 22 is the action part of this method, the part between the curly-braces. This line of code is adding the two variables together and displaying the answer to the Unity Console. Then, follow the ensuing steps:
- Go back to Unity and have the Console panel showing.
- Now click on Play.
What just happened?
Oh no! Nothing happened!
Actually, as you sit there looking at the blank Console panel, the script is running perfectly, just as we programmed it. Line 16 in the script is waiting for you to press the Return/Enter key. Press it now.
And there you go! The following screenshot shows you the result of adding two variables together that contain the numbers 2 and 9:
Line 16 waited for you to press the Return/Enter key. When you do this, line 17 executes which calls the AddTwoNumbers() method. This allows the code block of the method, line 23, to add the the values stored in the variables number1 and number2.
Have a go hero – changing the output of the method
While Unity is in the Play mode, select the Main Camera so its Components show in the Inspector. In the Inspector panel, locate Learning Script and its two variables. Change the values, currently 2 and 9, to different values. Make sure to click your mouse in the Game panel so it has focus, then press the Return/Enter key again. You will see the result of the new addition in the Console.
You just learned how a method works to allow a specific block of code to to be called to perform a task.
We didn't get into any of the wording details of methods here, this was just to show you fundamentally how they work.
Introducing the class
The class plays a major role in Unity. In fact, what Unity does with a class a little piece of magic when Unity creates Components.
You just learned about variables and methods. These two items are the building blocks used to build Unity scripts. The term script is used everywhere in discussions and documents. Look it up in the dictionary and it can be generally described as written text. Sure enough, that's what we have. However, since we aren't just writing a screenplay or passing a note to someone, we need to learn the actual terms used in programming.
Unity calls the code it creates a C# script. However, people like me have to teach you some basic programming skills and tell you that a script is really a class.
In the previous section about methods, we created a class (script) called LearningScript. It contained a couple of variables and a method. The main concept or idea of a class is that it's a container of data, stored in variables, and methods that process that data in some fashion. Because I don't have to constantly write class (script), I will be using the word script most of the time. However, I will also be using class when getting more specific with C#. Just remember that a script is a class that is attached to a GameObject.
The State Machine classes will not be attached to any GameObjects, so I won't be calling them scripts.
By using a little Unity magic, a script becomes a Component
While working in Unity, we wear the following two hats:
- A Game-Creator hat
- A Scripting (programmer) hat
When we first wear our Game-Creator hat, we will be developing our Scene, selecting GameObjects, and viewing Components; just about anything except writing our scripts.
When we put our Scripting hat on, our terminology changes as follows:
- We're writing code in scripts using MonoDevelop
- We're working with variables and methods
The magic happens when you put your Game-Creator hat back on and attach your script to a GameObject. Wave the magic wand — ZAP — the script file is now called a Component, and the public variables of the script are now the properties you can see and change in the Inspector panel.
A more technical look at the magic
A script is like a blueprint or a written description. In other words, it's just a single file in a folder on our hard drive. We can see it right there in the Projects panel. It can't do anything just sitting there. When we tell Unity to attach it to a GameObject, we haven't created another copy of the file, all we've done is tell Unity we want the behaviors described in our script to be a Component of the GameObject.
When we click on the Play button, Unity loads the GameObject into the computer's memory. Since the script is attached to a GameObject, Unity also has to make a place in the computer's memory to store a Component as part of the GameObject. The Component has the capabilities specified in the script (blueprint) we created.
Even more Unity magic
There's some more magic you need to be aware of. The scripts inherit from MonoBehaviour.
For beginners to Unity, studying C# inheritance isn't a subject you need to learn in any great detail, but you do need to know that each Unity script uses inheritance. We see the code in every script that will be attached to a GameObject. In LearningScript, the code is on line 4:
public class LearningScript : MonoBehaviour
The colon and the last word of that code means that the LearningScript class is inheriting behaviors from the MonoBehaviour class. This simply means that the MonoBehaviour class is making few of its variables and methods available to the LearningScript class. It's no coincidence that the variables and methods inherited look just like some of the code we saw in the Unity Scripting Reference.
The following are the two inherited behaviors in the LearningScript:
Line 9:: void Start ()
Line 14: void Update ()
The magic is that you don't have to call these methods, Unity calls them automatically. So the code you place in these methods gets executed automatically.
Have a go hero – finding Start and Update in the Scripting Reference
Try a search on the Scripting Reference for Start and Update to learn when each method is called by Unity and how often.
Also search for MonoBehaviour. This will show you that since our script inherits from MonoBehaviour, we are able to use the Start() and Update() methods.
Components communicating using the Dot Syntax
Our script has variables to hold data, and our script has methods to allow tasks to be performed. I now want to introduce the concept of communicating with other GameObjects and the Components they contain. Communication between one GameObject's Components and another GameObject's Components using Dot Syntax is a vital part of scripting. It's what makes interaction possible. We need to communicate with other Components or GameObjects to be able to use the variables and methods in other Components.
What's with the dots?
When you look at the code written by others, you'll see words with periods separating them. What the heck is that? It looks complicated, doesn't it. The following is an example from the Unity documentation:
Don't concern yourself with what the preceding code means as that comes later, I just want you to see the dots.
That's called the Dot Syntax. The following is another example. It's the fictitious address of my house: USA.Vermont.Essex.22MyStreet
Looks funny, doesn't it? That's because I used the syntax (grammar) of C# instead of the post office. However, I'll bet if you look closely, you can easily figure out how to find my house.
This article introduced you to the basic concepts of variables, methods, and Dot Syntax. These building blocks are used to create scripts and classes. Understanding how these building blocks work is critical so you don't feel you're not getting it.
We discovered that a variable name is a substitute for the value it stores; a method name is a substitute for a block of code; when a script or class is attached to a GameObject, it becomes a Component. The Dot Syntax is just like an address to locate GameObjects and Components.
With these concepts under your belt, we can proceed to learn the details of the sentence structure, the grammar, and the syntax used to work with variables, methods, and the Dot Syntax.
Resources for Article:
- Debugging Multithreaded Applications as Singlethreaded in C# [Article]
- Simplifying Parallelism Complexity in C# [Article]
- Unity Game Development: Welcome to the 3D world [Article]