You can think of variables as boxes to store some information to be referenced and manipulated in a program. We can use variables for the speed of a player, the current score of the game, the remaining lives, the skin color and basically for any element that needs a value in our games.
Creating a variable in C#
First of all, you have to create a script in Unity and attach it to a GameObject in your scene:
In order to create a variable in a C# script in your Unity project you have to follow this syntax:
Ok, lets explain each element of this line one by one:
- Access modifier: indicates where the variable can be used, public means that you can access from any script and private the variable can be used by code in the same class.
- Type: following the analogy from the beginning of the article, before storing something in the box we have to define what type of thing you can put in it. In C# the basic types are int (whole number), float (number with decimals), string (set of characters) and bool (true or false).
- Name: a label to identify your variable.
- Value (optional): The information to store in your variable.
Usually when we use variables we have to modify their values at some moment, for example, if the player is hitted by an enemy he loses a life, or if he picks up a power up increases the attack power.
To change the value you can use the assignment operator (=), and we can use the arithmetic operators (+, -, *, /) for different calculations:
The next code show you a simple “Player” script with some variables declared commonly used in many games: