Creating A Game Manager Class In Unity
Except perhaps, the tiniest of games, most games will need some sort of game manager to deal with data that affects the game in multiple places. Here, I will create one of my own.
Today’s Objective: Create a Game Manager to manage the game data and functions which are used by multiple parts of the game.
The Design:
Game Managers are commonly created using the Singleton design pattern, since there is usually only one of them, and it allows them to be accessed from almost anywhere. I’ll be using this pattern too.
In my case, the Game Manager class will manage the Pause/Restart/Quit gameplay functions, as well as an important game progression boolean.
The Code:
The general method (there are many variations) for creating a Singleton is like this:
This class component will be placed on a GameObject in the game scene. Usually it’s own GameObject, probably called “Game Manager”.
To have it do what I need it for, I will need to add some more variables and methods:
This Manager’s methods can now be accessed and called from any class in the scene.
You may have noticed that the audio management section of this manager is actually done in another class, the AudioManager.
Unlike the GameManager, the AudioManager is not a Singleton. This was a choice I made because I wanted to access all other managers through the GameManager, like:
I felt that this was a nicer implementation. It can only be accessed through the GameManager (or GetComponent of course).