A Venerable Variety of Variables — Understanding Variables in Unity

Variables are core construction block of working in C#, and in turn, Unity. Fortunately, variables are quite simple once you break them down to their basest form.

A variable is an identifier that stores a desired value of a type.

All variables have a Type, Name, and value associated with them.

Let’s look at a few examples:

A Boolean is a simple True/False check. You can name a Boolean ANYTHING, but it only holds a True/False check.

Let’s use an example you may need for a videogame;

The player can only open a door if they have the key for it (This example assumes there is only one key).

Think of a boolean like a question: “Does the player have the key?”

The boolean is named “Doeshavekey”, and is defaulted to false.

This variable type can only hold the yes/no, and is perfect for simple conditionals. When the player picks up the key, we can “flip” the bool to true, allowing them to proceed.

Next, an integer variable (int).

An int variable holds a whole number value.

In-game example; a scoring or currency system.

The integer variable is named “currentmoney”.

If you need to use decimal points for your tracked number value, we use float instead.

Float’s are very similar to Integers, but they can track decimals.

Floats are better used for movement systems or anywhere you may need fractional information.

As a parting note, in Unity you must specify variables as Public or Private. There are a few key differences to the two.

Public variables can be accessed by other scripts, and can be seen inside the Unity Inspector window (and edited there too).

My public speed variable can be changed from the Unity Inspector.

Keep in mind that any changes made in the Inspector OVERRIDE the script’s value.

Private variables cannot be edited by other scripts, and cannot be seen in the editor. Private scripts are generally used when the value tracked is only needed on the object it is attached to and does not need to be edited by another script.

There are more variable types in Unity, and we will cover them as we move forward with these tutorials!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jack Leavey

Jack Leavey

I am a software engineer with years of experience branching into game development, specifically in Unity. Follow along for guides on creating game mechanics!