In Unity, variables are used to store and manipulate data in your scripts. Variables can be of different types, such as integers, floats, booleans, and strings, and they can be used to store a wide range of information, including player input, game state, and object properties.

Here are some examples of different types of variables in Unity:

int: Integer variables

are used to store whole numbers. For example, you can use an int variable to store the player’s score.

int playerScore = 0;

float: Float variables

are used to store decimal numbers. For example, you can use a float variable to store the player’s movement speed.

float moveSpeed = 5f;

bool: Boolean variables

are used to store true or false values. For example, you can use a bool variable to store whether the player is alive or dead.

bool isAlive = true;

string: String variables

are used to store text. For example, you can use a string variable to store the player’s name.

string playerName = "John Doe";

Vector3: Vector3 variables

are used to store 3D vector coordinates (x, y, z). For example, you can use a Vector3 variable to store the player’s position.

Vector3 playerPosition = new Vector3(0, 0, 0);

GameObject: GameObject variables

are used to store references to GameObject

In Unity, variables can be declared in different places such as inside a script, inside a class, inside a method and so on. They can also be declared as public or private.

Public variables:

  • Public variables can be accessed and modified by other scripts. They are declared outside of any method and can be seen in the Unity editor, where you can change their values.
public float moveSpeed = 5f;

Private variables:

  • Private variables can only be accessed and modified within the script they are declared in. They are declared outside of any method and they cannot be seen in the Unity editor, they can only be modified via the script.
private float jumpForce = 5f;

Serialization

Another important aspect of variables in Unity is the concept of serialization, which allows Unity to save the values of variables to disk and reload them later, so that the values are preserved when the game is closed and re-opened. By default, Unity will serialize any variable that you declare as public, but you can also use the [SerializeField] attribute to make a private variable serializable, so that you can still modify it in the Unity editor.

[SerializeField]
private float health = 100f;

Built-in variable

In addition to these types of variables, Unity also provides a number of built-in variables that you can use in your scripts, such as Time.deltaTime, Input.GetAxis, and transform. These built-in variables give you access to various features and functionality of the Unity engine, such as time, input, and object properties.

In summary, variables are a fundamental concept in Unity, they are used to store and manipulate data in your scripts, allowing you to control the behavior of your game objects, and also you

Enumerations (enum):

  • Enumerations are a way to define a set of named integer constants. They can be useful to represent a set of related options, such as game states or input buttons.
enum GameState {Menu, Playing, Paused, GameOver};

Properties:

  • Properties are a way to define a variable with custom getter and setter methods. They can be used to add additional functionality to a variable, such as input validation or event triggering.
private int _health;
public int Health
{
    get { return _health; }
    set {
        if (value < 0) value = 0;
        _health = value;
    }
}

Constants:

  • Constants are variables that cannot be modified after their initial assignment. They are useful for values that are not expected to change during the execution of the program, such as pi or the speed of light.
const float PI = 3.14159265358979323846f;

Static variables:

  • Static variables are variables that exist independently of any instances of a class, meaning that there is only one copy of the variable shared among all instances of the class. They can be useful for values that need to be accessed by multiple instances of a class without creating additional copies.
public static int globalScore;

Nullable types:

  • Nullable types are a way to assign a null value to a variable. They can be useful when a variable is expected to be assigned a value, but it can also have no value.
int? playerLives = null;

These are some of the more advanced concepts related to variables in Unity, they will allow you to have more control over the data in your scripts, and make it more robust and efficient.

  • Enumerations (enum): Enumerations can be used to represent a set of related options, such as game states or input buttons.
enum GameState {Menu, Playing, Paused, GameOver};

public GameState currentState;

void Update(){
    switch (currentState)
    {
        case GameState.Menu:
            // Show menu
            break;
        case GameState.Playing:
            // Update gameplay
            break;
        case GameState.Paused:
            // Show pause menu
            break;
        case GameState.GameOver:
            // Show game over menu
            break;
    }
}
  • Properties: Properties can be used to add additional functionality to a variable, such as input validation or event triggering.
public class PlayerHealth : MonoBehaviour
{
    private int _health;
    public int Health
    {
        get { return _health; }
        set {
            if (value < 0) value = 0;
            _health = value;
            if (_health == 0)
                OnDeath();
        }
    }

    public event System.Action OnDeath;

    void Start(){
        Health = 100;
    }
}
  • Constants: Constants are useful for values that are not expected to change during the execution of the program.
const float gravity = 9.81f;

public class PlayerMovement : MonoBehaviour
{
    public float jumpForce = 10f;

    void Update(){
        if(Input.GetButtonDown("Jump"))
            GetComponent<Rigidbody>().AddForce(Vector3.up * jumpForce, ForceMode.Impulse);

        GetComponent<Rigidbody>().AddForce(Vector3.down * gravity * Time.deltaTime);
    }
}
  • Static variables: Static variables can be useful for values that need to be accessed by multiple instances of a

By Technology Researcher

Analyst studies emerging trends in the information technology.

Leave a Reply