Menu
CoddyTech

Game States

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

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

Cross the floor without touching the lava. The GameManager (a singleton) and the Lava script are there; give the game its states.

  • In GameManager.cs, above the class, declare an enum GameState with the values Ready, Playing and GameOver, in that order, and give GameManager a public GameState field named state. The game starts Ready.
  • While the game is Ready, Space starts it: the state becomes Playing and Go! is logged.
  • Lava calls HitLava(). While the game is Playing, that ends it: the state becomes GameOver and Game over is logged. Space never restarts a finished game.
  • In Player.cs, the arrows walk the player only while the state is Playing.

Press Play, try the arrows before Space, then walk into the lava, 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
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Building Real Games