A variable can be compared to a container that includes a value that may change over time. When using variables, we usually need to: (1) declare the variable by specifying its type, (2) assign a value to this variable, and (3) possibly combine this variable with other variables using operators, as illustrated in the next code snippet.
int myAge;//we declare the variable myAge
myAge = 20;// we set the variable myAge to 20
myAge = myAge + 1; //we add 1 to the variable myAge
In the previous example, we have declared a variable called myAge and its type is int (as in integer). We save the value 20 in this variable, and we then add 1 to it.
Note that, contrary to UnityScript, where the keyword var is used to declare a variable, in C# the variable is declared using its type followed by its name. As we will see later, we will also need to use what is called an access modifier in order to specify how and from where this variable can be accessed.
Also note that in the previous code, we have assigned the value myAge + 1 to the variable myAge; the = operator is an assignment operator; in other words, it is there to assign a value to a variable and is not to be understood in a strict algebraic sense (i.e., that the values or variables on both sides of the = sign are equal).
To make C# coding easier and leaner, you can declare several variables of the same type in one statement. For example, in the next code snippet, we declare three variables v1, v2, and v3 in one statement. This is because they are of the same type (i.e., they are integers).
int v4=4, v5=5, v6=6;
In the code above, the first line declares the variables v1, v2, and v3. All three variables are integers. In the second line of code, not only do we declare three variables simultaneously, but we also initialize them by setting a value for each of these variables.
When using variables, there are a few things that we need to determine including their name, their type and their scope:
string myName = “Patrick”;//the text is declared using double quotes
int currentYear = 2017;//the year needs no decimals and is declared as an integer
float width = 100.45f;//the width is declared as a float (i.e., with decimals)
myName = “My Name”
Common variable types include:
You can drag and drop this file to an empty object, play the scene and see the result in the Console window. You can also, if you wish, modify the file using Mono develop or any script editor of your choice.