Variables in Programming (Unity and C#)

Jose Gil
3 min readApr 2, 2021

When developing games or any program, you will need to store information and manipulate it as required. Variables perform this action. Typically termed the building blocks of programming, they are simply containers for storing data values that are known or not. Variables are also very useful to label data with descriptive names.

In Unity, the most common types of information in Variables are

  • Integers (int) — Whole numbers.
  • Floats (float) — Numbers with or without decimal values
  • Doubles (double) — Number with a double floating-point
  • Strings (string) — String of characters.
  • Bools (bool) — Boolean value (true or false)
  • Arrays (Array) — Data that can hold several objects
  • Objects (Object) — Class for other types
  • GameObject (GameObject) — base entities in Unity scenes

Defining Variables within Unity

When defining Variables, they must:

  • each have a unique name based on Alphanumeric characters.
  • not contain any symbols or spaces to avoid creating conflicts with other instructions.
  • use “Camel Case” notation (Use of lowercase at the beginning of the Variable name and uppercase at the beginning of the second and additional words
  • not use names of system functions

For example

public int myVar = value;
private bool myBool = true;

Variables can be either Private or Public.

Variables should be assigned an Access Modifier to the front of the statement to enforce access to the data. The two most common Access Modifiers are:

  • Public — access is not restricted.
  • Private — access is limited to the containing type.

Displaying Variables in the Unity Inspector

In the context of Unity, only Public Variables are displayed in the Inspector. Should you want a Private Variable to be visible in the Inspector [SerializeField] can be added before the Variable.

[SerializeField] private varName = data;

You are also able to hide a Public Variable in the Inspector with [HideInInspector]

[HideInInspector] public varName = data;

Organise your Variables in the Inspector

If you have a script with many variables, they can be grouped within the Inspector with the Header attribute.

[Header(“Parameters”)].

Best Practices with Variables

At Mooski Games, we use the following practices when developing in Unity

  • Always make Variables Private unless they need to be accessed by another script
  • Label private Variables with a leading underscore
  • Assign names that describe the use of the Variable correctly
  • Specifically, state if the Variable is Private or Public

--

--