My 120-day journey to being a better Unity developer — Day 6

Variables! — The building blocks of programming

Jean-Noel Seneque
3 min readMay 2, 2021

What are variables?

Variables are basically containers, storage space in memory (RAM) for the data we use in our games, such as a player’s health, a player’s name, or is the player poisoned.

Examples of different variable declarations

When a variable is declared there are three required components with an optional fourth.

This first part is the Access modifier. We control if other classes and methods can access the contents of this variable. The two most common are public and private.

Public: Any class and method can access this variable. These public variables can also be seen in the Unity Inspector.

Private: Only the class and its methods in which the variable was declared may access it. These variables can not be seen or changed in the Unity Inspector.

Note: By using the [SerializeField] attribute before the private declaration of a variable, allows the variable to be seen and edited in the Inspector but still provides private access.

Example of the SerializeField attribute

The second part is the data type of the variable where we specify what this variable is going to be storing. In the image above, the variable can only store float values.

The third part of the declaration of a variable is the name of the variable. This is an alias provided that points to the memory address. There are a few rules you need to consider when naming a variable.

  1. Name the variable with its purpose so the reader can easily identify it
  2. Naming is to be typed as Camel case where the first letter is in lower case and then every first letter of a new word is in upper case. There is no spacing between words.
  3. Private variables are indicated with an underscore prefix.
  4. Can not name the variable by keywords the programming language already uses.

The fourth optional part is the assignment of default values. It is optional because you may assign a value after you declare it or you may assign a value at declaration. Here is an example of both cases:

Assigning value examples

If you enjoyed reading this article, and you want to see more like this, click on the Follow, so you may be notified of future releases. You may also send me a message if you need any further help.

--

--

Jean-Noel Seneque

A Data & Analytics Consultant who is expanding into developing experiences in XR, Enterprise and Gaming space using Unity www.jeannoelseneque.com