The Singleton Pattern In Unity

Singletons are a good way to represent global variables in your program. Despite debates surrounding the use of Singletons and global variables, They are especially useful when developing manager game objects.

First create a private variable that other classes will access of the singleton. In my case this will be _instance;

To avoid being able to change the value I need to create a property that will return that value. Do a null check to make sure that the instance is there, otherwise it will debug the error.

In the awake method I am assigning the singleton to the class.

That is the basic setup for a singleton class. There are other things you could do like make sure that this object is passed between scenes.

Consider a property that represents the player public bool HasCard below. We can set and retrieve it based on how its declared. In order to do this we simply access it through the Instance member

This is the value of the Singleton and why its basically a way to hold global information


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