A Venerable Variety of Variables — Understanding Variables in Unity
Variables are core construction block of working in C#, and in turn, Unity. Fortunately, variables are quite simple once you break them down to their basest form.
A variable is an identifier that stores a desired value of a type.
All variables have a Type, Name, and value associated with them.
Let’s look at a few examples:
A Boolean is a simple True/False check. You can name a Boolean ANYTHING, but it only holds a True/False check.
Let’s use an example you may need for a videogame;
The player can only open a door if they have the key for it (This example assumes there is only one key).
Think of a boolean like a question: “Does the player have the key?”
This variable type can only hold the yes/no, and is perfect for simple conditionals. When the player picks up the key, we can “flip” the bool to true, allowing them to proceed.
Next, an integer variable (int).
An int variable holds a whole number value.
In-game example; a scoring or currency system.
If you need to use decimal points for your tracked number value, we use float instead.
Floats are better used for movement systems or anywhere you may need fractional information.
As a parting note, in Unity you must specify variables as Public or Private. There are a few key differences to the two.
Public variables can be accessed by other scripts, and can be seen inside the Unity Inspector window (and edited there too).
Keep in mind that any changes made in the Inspector OVERRIDE the script’s value.
Private variables cannot be edited by other scripts, and cannot be seen in the editor. Private scripts are generally used when the value tracked is only needed on the object it is attached to and does not need to be edited by another script.
There are more variable types in Unity, and we will cover them as we move forward with these tutorials!