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
EasyGive the lava crossing three states.
- Declare
public enum GameState { Ready, Playing, GameOver }above the GameManager class, andpublic GameState state;in it. - In
Update(), while Ready, Space sets Playing and logsGo!. InHitLava(), while Playing, set GameOver and logGame over. - In
Player.cs, read the arrows only whileGameManager.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
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input SwapPractice on your own: Unity playground