Variables are key to getting your game to act like a game and be able to interact with it. To get started with variables you need to understand each of the parts of a variable declaration.

First, you need to declare whether the variable will be public or private. A public variable can be accessed by other classes in other parts of your program. A private variable can not. It can only be accessed in the class that it is declared in. A public variable will also allow you to interact with the variable in the Unity editor like in the image below. At the end of the article we will show you how to make it so you can interact with a private variable in the same way, while still keeping it private from the rest of your project.

Next, you need to set the type of the variable. There are many different types that you can choose from. Here I will only go through four of the basic ones you can use.

int — this is an integer or a whole number like -5, 0, 2, or 432942.

float — this is a number with a decimal in it like -5.3, 0.31, 2.5, or 12345.6789.

bool — this has two values true or false.

string — this a group of characters in quotation marks like “Hello World!” or “Good Luck Adventurer.”

After the type is the name you give the variable. In my example above I called it “speed”. This is the name that you will use to reference the variable in other places within your program. You can use the reference to change the value of the variable by assigning it a new value. Or you can use it to get the value you have assigned to it. In the example below I am using the speed variable. When the program runs speed will be replaced by the value that is assigned to it.

Last, you have the option of assigning a value to the variable by typing an equal sign and then the value. You need to make sure the value that you are assigning to the variable is the same type that you declared the variable to be. In this example I made a float so I need to put an “f” after the number so that the computer will know it is a float.

One last thing, I mentioned before that if you want to interact with a private variable from the Unity editor you need to do something special. To get it to work you need to add “[SerializeField]” to the line above the variable. That will allow the Unity editor to interact with the variable.

That is enough to get you started with variables. Now it is time for you to go try, experiment, learn!

Good Luck Adventurer!

-Chris