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

Library vs Framework

Announcing the Binance Chain (BEP2) and Binance Smart Chain (BSC) payment integration

HEPiX conference

A Simple Concept called Web Scraping

Part 2, UI Widgets from scratch in Jetpack Compose.

7 Methods to Fix Windows Update Error 0x80072EFF

DevOps Tools

Python Memory Management

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

How to Add Custom Post Processing Files to Individual Cameras in Cinemachine

2D Mobile: IDamageable Interface

Saving Data in Unity3D Using Files

Creating an Audio Manager in Unity