Variables in programming
The building blocks of programming
When programming, there are these “things” we have to use, yes, have to, called variables. Some will say they are like droors or boxes that contain certain information. To generalize, they are containers which hold temporary information used by the program which can change variably.
Variables must be declared within the code as follows:
Variables can be declared as public or private.
When declared as public, a variable can be accessed and modified by other script in the program.
When declared as private, a variable can only be accessed by the script in which it resides.
Variables can contain several types of information. Some of the most common types are as follows:
- String : These variables will contain a sequence of characters or letters. “Hello”
- Int: integers are whole numbers, they don’t havedecimal places. 25
- Char: character variables will hold only one character. “A”
- Float: floats are numbers with decimal places. It has a precision of 32 bits. It is important to note that when assigning a value to a float variable, it must be followed by a lower case f. 3.14f
- Double: doubles are like floats but can hold a larger number of decimals (64 bit precision) and take up more memory than a float. They don’t need the “f” after the number assignment.
- Bool: booleans are either true or false. They answer yes or no questions. Is the light on = true, is the light off = false
Although there are several ways to write a variable name, it is recommended that variables have a descriptive name, this way it is clear as to what it does.
We normally use cammel case when writing a variable name. This is where we always start with a lower case letter but the first letter of the second and/or third, etc, is capitalized:
For private variables, convention dictates that they start with an underscore. This makes themeasier to spot inside the code.
Like the name implies, the values stored in variables can be changed. For example, if you are keeping score in a game, it will increase or decrease over time. If you have an inventory of items, it will also change throughout the game. This is called reasigning a variable.
As we can see, variables only need to be declared once. After that we only need to reference the variable name and give it a new value that meets its type.
Even though Unity has other variable declarations, these are the most common types used. We will most likely see the other types later on.