How to Create the Singleton Design Pattern in Unity & C#

A Singleton is a programming pattern that allows you to access a class script without using a GetComponent reference. It is an excellent tool to use for creating Manager Classes because it makes the code contained within them easy to reference and access from anywhere. Let’s walk through creating a Singleton GameManager.

Step 1 in creating a Singleton is to create a static variable that can be used to access this class. A static variable can be accessible from any other class. You do not want to use it for most variables for this reason, but it is useful for Manager classes because there will be only one instance of those classes — one GameManager, one AudioManager, one UIManager and so forth.

We keep this first static variable private because we do not want any other script to be able to change the value of _instance and it will always be assigned to this GameManager.

Next we create a property — just like a variable but we open it up with squiggly braces and add an additional line for get and set. This line defines that you can get the value of the property or set the value of the property.

If you need to control this further, you can specify “private set;” to indicate that any class can get the value of this variable but only this class can set that value.

Now, we can also execute code before getting or returning the value of the variable we have created. We do this by creating squiggly brackets after each into which we can input the code to execute:

In this case we wish to return _instance which will give us access to this script. For creating a singleton however it is very important that we never let another script set the value of this instance, so we will only use “get” here:

When we input “return _instance”, it means that when we reference the public Instance (capital) from another script, when that executes we will be given access in this script to the private static variable, allowing us to run the code contained within our GameManager Singleton.

It is also important that we null check here to be sure our GameManager remains properly connected before running this code:

Finally, we can assign our new _instance variable in void Awake() so it is assigned as the game is loading. We set _instance equal to this script that the GameManager object is attached to.

Now our Singleton design pattern is complete and ready to be used! Here is how it looks all together in finished form:

In my next guide I’ll cover using the Singleton pattern to control our GameManager script with some specific implementations. See ya there!

Unity Developer from Los Angeles, CA