Unity Coding — Variables

Christopher Graf
3 min readMay 3, 2021

--

Coding can get to be extremely complicated once you reach advanced techniques and algorithms. But it is simpler when you look closely and break it down to smaller parts. The main building blocks of all code are variables. Let’s take a glance at these and how they are the basis of almost everything we do.

There are four main types of variables. These are integers (whole numbers), floats (real decimal numbers), strings (collection of characters), and booleans (true or false). In the picture below, lets take a look at some variable declaration representing a certain famous video game character.

With a name or any other text, a string is the perfect variable. These can even be a full sentence or longer. Any whole number is best shown as an int, like age or amount of items. Sometimes a number or degree can have decimals places. Maybe a character’s running speed or attack power. Floats are your best bet here. Finally, any true or false statement can be held as a bool. This can decide whether or not a door opens depending on if the player has the proper key or if they have a certain ability.

In the example, you may have also noted the ‘private’ in front of every variable declaration. This means that these variables are only accessible in this script. It is best to make your variable private by default, but what if you wanted another script to access them. You simply change that ‘private’ to ‘public.’ Look what else happens in Unity when you make your variables public.

When you click on the object containing your script, in the Inspector you’ll see those variables show up. When they are here, you can completely change them without having to go back into the script. This is extremely useful for testing. But what if you want this Inspector advantage, but still want to keep your variables private? There is a simple solution to that.

Simply add ‘[SerializeField]’ in front of any private variable and it will show up in the Inspector, same as if it were a public variable.

There is one more diversifier in variables that we should discuss. The ones you have seen so far were declared at the top of the script, right under the class name and not inside of a function. This means that they are global variables and can be accessed at any point within this script. In another article on coding player movement, we declared two floats inside of the Update() function.

These are called local variables. They only exist and can be accessed within the Update() function because that is where they were first declared.

These are all the basics you need to know to start making your own variables. You can even start by changing that 3 in the transform.Translate example to be a private float speed variable. Make it serialized and see how quickly you can test out different speed for your moving player. You are in control now.

--

--

No responses yet