Creating Manager classes with Singleton pattern

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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Custom UI Master Class: Dropdown Menu with TextField

“Anima of Quantmix” Official Service Begins!

GSoC Week-7 @ OpenMRS

FOREX Algorithmic Trading with Python and Meta-Trader 5 (part I)

Building Simple Dot Com Game

Big Data Analytics with Spark in Azure HDInsight

iOS friendly development for Android Developer

Largest Submatrix With Rearrangements

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
Hernando Nieto Jaramillo

Hernando Nieto Jaramillo

Unity developer

More from Medium

Cleaning up the Homing Missile code

Hidden Shortcuts to Make Level Design Easier in Unity.

Managers, Main Menu and Loading screen

Day 102: Character Animation Part 5