Setting Up The Singleton Pattern In Unity
Singletons are a design pattern used in object oriented programming. They are a good way to represent global variables in your program. Despite debates surrounding the use of Singletons and global variables, they are very useful in Unity Development. They are especially useful when developing manager game objects.
In the code below I set up a basic Game Manager Singleton class to be used in a Unity project:
The first private static member of the class is the instance of the Singleton. In this type of class, you don’t actually instantiate objects of the class. This is why we have static members, so you can call the class and access its members without instantiation. It is possible to have static members in other types of classes, just know when you access the static member it will hold the same value across all objects belonging to the class.
The public property basically gives us a reference to the Singleton. If the Singleton is not null, it will return the private member.
The Awake method is a Unity behavior. What happens here is that when this method is called it will initialize _instance to our current game object.
Consider a property that represents the player’s score, as above. We can set and retrieve the score based on how its declared. In order to do this we simply access it through the Instance member. Something like:
The Score can be accessed like this from any other script in the project. This is the value of the Singleton and why its basically a way to hold global information. This, by the way, is also why it is very useful in setting up manager classes in Unity.