Day 5 | A Simple Intro to Unity Variables
This article will explore variables in Unity/C#. It’ll cover what they are, the different basic types, other descriptors that can be attached to them, and a quick example of how to use them.
What Are Variables?
Variables are text-based names used as containers to store one or more values that can be referred to later in a computer program.
Basic Variable Types
float: A variable that contains a numeric value with a decimal. If you’re assigning a float value to a variable, you’ll need to add the “f” character after the value.
int: A variable that contains an integer value.
bool: A variable that contains a true or false value.
string: A variable that contains a sequence of characters as a value.
Variable Accessibility Keywords
private: This keyword indicates that a variable is only accessible by the script/class that it resides in. As a general tip, it’s recommended to keep most variables private unless you have a clear idea as to why you are using another keyword instead.
public: This keyword indicates that a variable is accessible to other scripts/classes and be manipulated by them.
SerializeField: In Unity, private variables are not shown in the Inspector. However, if you need a designer to access private variables from the Unity Inspector, but you don’t want them to touch the code, SerializeField will do exactly that. Add [SerializeField] above a private variable to expose it in the Inspector window.
private int demoValue;
HideInInspector: In Unity, public variables are shown in the Inspector. If you don’t want a designer to touch the value from the Inspector, but you need the variable to be accessible across different scripts/classes, HideInInspector will do exactly that. Add [HideInInspector] above a public variable to prevent it from appearing in the Inspector.
public int demoValue;
A Quick Example
We’ll write a small script to show how to initialize and reference a variable in Unity. Our script will print out the value of a variable that we will initialize. To initialize a variable, you’ll need at least 3 components and optionally a 4th:
- Accessibility Keyword: private/public
- Variable Type: float, int, bool, string, etc.
- Variable Name
- (Optional) A value to assign the variable
Then, in the Unity Start function, we’ll use a Debug.Log() statement to print out the value in the console. Here’s what I have.
After running it, we find that the value printed by the Console is 0 as planned.
Now we can add an Attribute to the variable so that we can edit the value from the Inspector. We add [SerializeField] above our variable, edit the number in the Inspector, and now, the console prints the value from the Inspector.
This is a small intro to Unity variables to help get you started! Good luck!