Singleton design pattern in Unity

Tristan Engel
3 min readOct 7, 2021

--

In this article we will set up our game manager using singleton design pattern. This means there will be only one of this in the game and it will be in memory always. This allows other scripts to always access it. There for there is no need to use GetComponent.

Static

Putting static before our type makes it always stay in memory. We did it for our class so now our class is always in memory. This is useful when we only have one of it in the scene.

Properties

Now we can create properties. Just like you see on the transform.position tooltip it says get, set. Which means we can get the value and set the value. In our case, the game manager, we don’t want other script to set the game manager to something else so we only setup get.
Next we can add some code for when get is called. We do a null check.

Assign

In Awake() of our game manager script we assign the game manager to itself.

Public method in our static class

We want to have a variable that keeps track if the player has taken the keycard or not. In our game manager script we create the following function. In it we set the properties get and set to be available. This is now available to use from other scripts.

Access from other Scripts

From our other script we could of course use GetComponent to get the game manager then call public function in our game manager script. The power of this singleton method is we can just call the class directly without using get component.

This way we can easily change the value of HasCard to true and other gameobject can access it easily too.

Downside

The downside of using singleton on manager classes is that Unity doesn’t see the properties/public variables in the inspector. Only if debug mode is turned on in inspector we can see it.

--

--

Tristan Engel
Tristan Engel

Written by Tristan Engel

Aspiring developer that’s self-learning Unity & C# to transition to a career with Unity. I got a passion for creating interactive experiences.