Tip of the Day: Manager Classes & Singleton Pattern in Unity

Mohamed Hijazi
Level Up Coding
Published in
2 min readApr 21, 2021

--

When creating your project, you will encounter a case where you want to manage different player states, take control of the game’s audio, or for example, take control of loading scenes or controlling the UI.

Each one of these cases (and many more) can be put in a separate manager class. For example: GameManager, UIManager, AudioManager, etc.

Usually these manager classes are persistent through your game, and they would want to communicate with the different scripts in the game. You can get the gameObject instance holding these managers in each script you want to use them, but then you would fall into too many dependencies and your code might be prone to errors.

In order to achieve this, we can use a Singleton Pattern. This allows the Manager class to be easily accessible from other classes, and they get hold of the global variables and methods easily.

Singleton Pattern

In the manager class, first create a private static instance of the manager, and also create a public getter for this instance. Making it static will it to be accessed by other scripts. Finally in the Awake method, set the private instance to this manager class.

Now in order to access this manager class from other scripts, just call the public Instance.

GameManager.Instance.(your public variable or public method);

But having to type this singleton for every pattern can be tedious, so how can we streamline it?

We can create a separate script that holds the singleton code and then the manager classes can inherit this singleton class. So, create a C# Singleton Script.

The “T” component will be used while inheriting to check for the script component.

Now when creating the manager class, simply inherit the Singleton script and you are all set, your manager class is now a Singleton

public class GameManager : Singleton<GameManager>
{
void Start()
{
}
void Update()
{
}
}

--

--

A knowledge seeking biologist who is following his passion into a full time career in Unity / Game Development. https://www.linkedin.com/in/mohamed-hijazi/