Game Programming Pattern: Singleton

Simon Leen
2 min readAug 12, 2021

--

Objective: Explain how and why we use it.

As shown in the last post, the Singleton Pattern can be usefull when it comes to a class that there will only be one instance of. This is why it’s great for use with a manager system such as a UI, Spawn or Game Manager.

The Singleton gives global access to the class, which can be accessed a lot easier than using GetComponent or GameObject Find with Tag and so on. Instead you can call it directly within any class.

The above code represents a general approach to how we would create the handle to the game manager and assign it before we can access any public methods within. For the most part, this is perfectly fine and works without issue but there is a better way.

In creating a Singleton we use a static variable of the class which will have properties assigned which can allow the other classes to call(get) and set properties that have been logically set.

The above is the GameManager/Singleton we used in the last post. Notice the HasCard bool. It is nice and simple and just requires a true or false. If we take into account the variation we showed in the previous code image, without a Singleton class you would need to create a handle by creating a private GameObject then in the Start method assign it using the Find and GetComponent before being able to call the public HasCard and setting it.

Now, take the above single line of code. No Handle and no Find or GetComponent. With the Singleton in use this is how simple it becomes to set the properties from any class without having to go looking for it.

--

--

No responses yet