Day 5: Using Variables in Unity
Variables are like little boxes of data that can be modified and accessed in our scripts. They are incredibly useful for keeping track of all kinds of data in a game or program; we can store names of objects, how much damage a weapon deals, the score of the player, and can control how these interact much more easily.
To make a variable, we need three things:
- Access Modifier (public or private). This tells us who can access the variable and the data it contains. If it’s private, then the variable can only be used in the class where it’s defined. If it’s public, then the variable can be used by other classes and can also be seen and modified in the Unity inspector window. Generally, variables should be private unless we plan to use them from other classes, or set them in the inspector.
- Type (int, string, float, or any other data or class type). This tells us what type of data or object can be stored in the variable. An int stores integer numbers (like 2, 50, or -60). A string stores a written word like “Score” or “Game Over”. A float can store a decimal number (like 5.5). C# is a strongly typed language, which means these data types are required so that the computer knows how to handle them in our code.
- Identifier. This is the variable’s “name” which is what we use to access its data. We may name a variable whatever we like, in order to keep track of its use in our code. For example, if a private variable is to keep track of the player’s score, we can use _myScore as its identifier. It’s a good idea to capitalize the first letter of each word to keep it readable, and to put underscores in front of private variables so we can tell at a glance that it’s meant for use only within this class.
If you would like to know more about variables and data types, you can check out this C# tutorial site.
The great thing about using variables in Unity, is that we can change the data they contain at any point, either through code or through the Unity inspector.
Here’s we set mySpeed as a public variable, and use it to determine how fast the player should move in the Update method.
We can change the speed variable as the game is running, and the player square will move faster, slower, and even backwards as the speed changes value.
Variables can also store much more complicated types of data used by Unity. For example, we can store the transform object of the camera in a variable, and then use it in our code.
After starting the game, this will tell us information about the camera’s position and print it to the console.
Variables are very powerful tools that we will be using throughout this Unity adventure. They are key for keeping code readable and easily modifiable.