Creating Manager classes with Singleton pattern

Hernando Nieto Jaramillo
2 min readAug 8, 2021

A GameManager is in meant to deal with stuff such as loading scenes. A way to communicate with it is using GetComponent method, but now we will use the Singleton pattern

When to use it?

When working with managers like AudioManager, GameManager, UIManager

Process

  • Create this line of code. It is private because we don’t want it to be modified outside
private static GameManager _instance;
  • Create a public static property. It will be accessed from outside and return the _instance value
public static GameManager Instance
{
get
{
if (_instance == null)
{
Debug.LogError("GameManager is null");
}
return _instance;
}
}
  • Set the _instance value in Awake
private void Awake()
{
_instance = this;
}

Why is it good?

Because it ensures there will be only 1 instance of the class
Also, the public class and its static variables can be accessed easily from any other class
Static variables are stored in memory

Example
Let’s say we have a bool hasCard in GameManager.cs
An approach is

But there is an issue: if the GameManager’s gameobject name is changed, the code won’t work

Here, the same code using a Singleton

Take on account: properties are not visible in Normal mode in inspector, you must change it to Debug mode

--

--