Singleton Design Pattern in Unity Programming

Marcus Ansley
3 min readJun 20, 2021

--

As a short and sweet definition (one which I found on here), the singleton design pattern ‘ensures that only one object of its kind exists and provides a single point of access to it for any other code’.

This pattern particularly comes in handy when we want to have a quick and easy way of accessing an instance of a class when we know this will be the only instance of that class in the scene. A common example of this kind of script would be some sort of manager class, like a ‘GameManager’ or ‘GameController’ class. The syntax for creating a Singleton tends to look something like this:

We create a static, private instance of the script (‘_current’) but restrict the way in which outside classes can access it. They have to instead use this public property ‘Current’ to have the instance returned to them, and (since we’re not including a ‘setter’ in this example) are unable to change this instance. The _current instance is currently being set as part of the Awake method here, but I’ve also seen scripts which tend to use a null check (like the one above) to create a new instance or assign one if it’s currently null:

This all allows us to, from anywhere in the program/from another class, access a singular instance:

This can be a lot tidier than needing to use GetComponent or needing to use a Find method just to access a script we know there’ll only be one instance of.

As a quick note, I’ve also seen code a bit like this from time to time, which can be useful if you want to have a persistent singleton in Unity (i.e. a single instance of a class which will follow the player around from scene to scene without getting destroyed):

It’s a bit clunky, especially with that FindGameObjectsWithTag search, but will essentially mean that if we reload the scene where this class was located by default it’ll destroy itself (upon realising there’s already an instance of this class) 😉

--

--

Marcus Ansley
Marcus Ansley

Written by Marcus Ansley

Game Developer | Game Design and Literature Graduate

No responses yet