Game Programming Pattern: Singleton!

addam davis
3 min readSep 30, 2021

Objective: Implement the singleton design pattern!

Singleton Design Pattern is a game design pattern that allows you to access the managers with out needed the get component function. This works well with the manager classes because it has one instance along all the classes. In this tutorial I will show you what you need to implement the singleton pattern.

Open the audio manager script we created in the last tutorial and delete everything.

Setting up a singleton pattern requires only a few things. First, in order access the singleton it has to be embedded in memory and span across all classes. To do that we need a static variable instance that is going to be designated for this class.

You also need need a property to access that instance. A property is like a variable except you can open them with {} and insert executable code into them. We want to use the get property.

Every property needs a return. In this instance we want to return the _instance. Now, when you access the Instance it is going to return the _instance which is going to be used in this script to give us access to the static reference.

we want to make sure there is only one in the scene and this can be done using a null check.

We need to create a void awake method. This method is called when the game is loading. Inside this method we want to assign the _instance variable to this script, this object that this script it on.

This is everything you need to set up your singleton design pattern. Now, instead of having to use a get component command to communicate with the audio manager.

We no longer need to us get component, the singleton is embedded in the memory and all classes have access to it.

That is all there is to it. You know what a singleton design pattern is, how to create it, and how to call upon it. Using a singleton is quick and easy, just remember, they only work on things that are instanced only once, like the managers. I’ll see you in the next tutorial!

--

--