Every variable we want to use in a script must be declared in a statement. What does that mean? Well, before Unity can use a variable; we have to tell Unity about it first. Ok then, what are we supposed to tell Unity about the variable?
There are only three absolute requirements for declaring a variable and they are as follows:
The following is the syntax we use for declaring a variable:
typeOfData nameOfTheVariable;
Let's use one of the
LearningScript
variables as an example; the following is how to declare a variable with the bare minimum requirements:
int number1;
The following is what we have:
number1
can store, which in this case is an int
, meaning an integernumber1
The second requirement of naming a variable has already been discussed. The third requirement of ending a statement with a semi-colon has been discussed. The first requirement of specifying the type of data will be covered next.
The following is what we know about this bare minimum declaration as far as Unity is concerned:
public
modifier which means it's private
by defaultnumber1
defaults to zeroThis section only shows the most common built-in types of data that C# provides for us and that variables can store.
Just these basic types are presented here so that you understand the concept of a variable being able to store only the type of the data you specify. The custom types of data that you will create later will be discussed in Chapter 7, Creating the Gameplay is Just a Part of the Game in the discussion of Dot Syntax.
The following chart shows the most common built-in types of data you will use in Unity:
We know the minimum requirements to declare a variable. However, we can add more information to a declaration to save our time and coding. We've already seen some examples in LearningScript
of assigning values when the variable is being declared and now we'll see few more examples.
18.118.31.67