The Singleton Pattern with Manager Classes

What is a singleton pattern? What are managers? Let’s have a look!

Manager Classes

A manager class represents a script that manages objects or data of a specific game element, similar to how a manager of a company would manage staff for different departments.

For instance, the GameManager script will control the state of the game. The AudioManager script will control the sound of the game. The SpawnManager will control how spawning of game objects.

Singleton Pattern

The singleton pattern is a commonly used design pattern. It allows for one instance of a particular class. They work well for Manager type classes.

Instead of using a GetComponent to communicate with other scripts, we can directly access a singleton class and its properties via its static instance.

For example, here’s a way to communicate with another script by using GetComponent:

var gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
gameManager.HasCard = true;

And here’s another by using the singleton pattern:

GameManager.Instance.HasCard = true;

Simple and clean.

The Singleton pattern and GameManager

I want to know if the player has triggered a specific cutscene. If triggered, then I want to set a bool to true, so that the player can complete the level.

The GameManager script will have this bool since it controls the state of the game.

I want to turn it into a singleton class to communicate with the trigger script and set the bool to true when triggered.

We want to create a private static variable of the same type of script. It’s going to be the instance to access the GameManager class.

private static GameManager _instance;

We also need to create a property of it.

public static GameManager Instance
{
get
{
if(_instance == null)
Debug.Log("GameManager is null");

return _instance;
}
}

Lastly, we want to make sure that _instance is assigned to the script in the Awake() function.

private void Awake()
{
_instance = this;
}

If I add a bool to see if the player has obtained a key card in the game manager class, I can access it from other scripts by typing:

GameManager.Instance.HasKeyCard = true;

Conclusion

Singletons allow you to access specific game manager-type scripts without having to worry about passing around references by using GetComponent.

It makes your code simple and clean, but it can be a bad practice to use them for everything. Limit the use of singletons to some manager classes that need only one instance of a class.

That is all for today. Thank you for your time!

Gabriel

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gabriel Perez

Gabriel Perez

102 Followers

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.