Game State System

The Game State system allows you to easily organize your game into states, managing things such as time freezing, enabling/disabling input, locking/unlocking and hiding/showing the cursor, and activating/deactivating objects such as menus.

With the Game State system, you can create any number of different states, and the game can only be in a single state at any given time. This makes it easy to organize things and to know which code is supposed to be running and when.

Game State Manager

To begin, add a Game State Manager component anywhere in your scene.

The Game State Manager is the core component of this system. It is a singleton, which means there must be only one of them in the scene at any time. The current game state can be easily accessed from any script, like so:

GameState currentGameState = GameStateManager.Instance.CurrentGameState;

Game States

A Game State is a Scriptable Object that represents a single state that your game can be in. Examples would be 'Gameplay', 'PauseMenu', 'GameOverMenu', 'ControlsMenu', etc.

To create a new game state for your game, simply right click anywhere in the Project tab and select Create > Game State. You can name it anything you want.

Game State Instances

You've created a new Game State, but you must add it to the Game State Manager. Create a new entry in the 'Game States' list in the inspector of the Game State Manager component, set the 'Game State' to the one you just created, and configure the parameters.

You can set a number of parameters for each game state, including whether time is frozen, and whether the mouse cursor is shown.

Entering A Game State

To enter a game state, you can either set the 'Starting Game State' reference on the Game State Manager, which is the game state that the game will start off in, or you can run the following line of code from anywhere:

// Pass a reference to a Game State

The game state you pass must have been already added to the game state manager, see the previous section above.

Game State Enabler

The Game State Enabler component enables you to run functions when any one of a number of specified game states are entered, without writing any code.

Simply add a Game State Enabler component anywhere in the scene, set the compatible game states, and add your functions to the 'On Compatible Game State Entered' and 'On Incompatible Game State Entered' events. This component will automatically connect to the Game State Manager in the scene and run the events at the right time.