The Singleton Programming Pattern

Today, I want to give an intro to the Singleton programming design pattern, and it’s use in Unity game development.

Vincent Taylor
2 min readNov 18, 2021

The Singleton Design Pattern is one of the many software design patterns, and is also one of the 7 most commonly used patterns. It is one of the simplest in both intention and implementation:

Ensure that a class has only one instance and provide a global point of access to it.

A class that is a Singleton cannot have multiple instances existing at any point in time. There must only ever be one instance of the class.

Implementation:

In C#, a Singleton is created by having a class with a static variable of the same type as the class itself. Something like this:

There are different variations in which it is not private, or is an auto-property. It just depends on your design choices.

Apart from the variable to hold the reference to the class instance, a Singleton also needs a globally-accessible way for other classes to access the instance. Again, different variations can do this differently depending on the above, but here’s what it would generally look like to fit the above variable:

Finally, a Singleton reference needs to be set as soon as possible. That would generally look something like this:

If _instance is not null, it means there is more than 1 class instance in the scene, so delete all except the first, to keep it as a Singleton.

Usage:

The Singleton Design Pattern is best used in cases where there should only ever be one instance of a class, such as game managers, global systems, or perhaps even the player manager.

It makes such classes accessible from anywhere in the scene, without the need for a reference to the object holding the Singleton class.

--

--

Vincent Taylor
Vincent Taylor

Written by Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.

No responses yet