Menu
CoddyTech

Game States

Part of the Building Real Games section of Coddy's Unity journey. Lesson 14 of 60.

A game is in one state at a time: waiting for the player, running, or over. Two bools such as isPlaying and isOver can both end up true by mistake, and a string such as "Playng" compiles and never matches. C# has a type for a fixed list of choices, the enum. This crossing light uses one:

public enum Signal { Red, Yellow, Green }

public class Crossing : MonoBehaviour
{
    public Signal signal;

    void Update()
    {
        if (signal == Signal.Red && Input.GetMouseButtonDown(0))
        {
            signal = Signal.Green;
            Debug.Log("Walk!");
        }
    }

    public bool CanWalk()
    {
        return signal == Signal.Green;
    }
}

enum Signal { Red, Yellow, Green } makes a new type with exactly three values, written Signal.Red, Signal.Yellow and Signal.Green. A Signal field holds one of them at a time; you compare it with == and change it with =. A misspelled Signal.Gren is a compile error, so the mistake shows before you press Play.

The enum is declared outside the class, so every script can use Signal, and a pedestrian's script can ask crossing.CanWalk(). A new enum field starts at the first value, here Red. In the Inspector a public enum field shows as a drop-down list of its values. Underneath, each value is a number counted from 0: (int)Signal.Green is 2.

challenge icon

Challenge

Easy

Give the lava crossing three states.

  1. Declare public enum GameState { Ready, Playing, GameOver } above the GameManager class, and public GameState state; in it.
  2. In Update(), while Ready, Space sets Playing and logs Go!. In HitLava(), while Playing, set GameOver and log Game over.
  3. In Player.cs, read the arrows only while GameManager.Instance.state == GameState.Playing.

Press Play: the arrows wait for Space. Then Check.

Try it yourself

using UnityEngine;

// Declare the GameState enum here: Ready, Playing, GameOver

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;
    // a public GameState field named state

    void Awake()
    {
        Instance = this;
    }

    void Update()
    {
        // While Ready, Space starts the game and logs Go!
    }

    public void HitLava()
    {
        // While Playing, the game is over: log Game over
    }
}

All lessons in Building Real Games

Practice on your own: Unity playground