The Singleton Pattern

Ryan Sweigart
3 min readJun 26, 2021

--

Objective: Create a game manager that other classes can access as needed.

We can us a singleton pattern to create a game manager to “remember” things about our game. In this case, we’ll use it to check if our lovable rogue has obtained the key card from the sleeping guard.

First we’ll create a static variable of the same type as our class — GameManager. A static variable is shared among all instance of a given class, but in the case of a singleton, the point is that there will only ever be one instance.

Next we’ll create a property named Instance. A property has a get method and a set method, each of which may contain a block of code. In this case, we will only allow other classes to get information from our Instance. When another class calls on the Instance, we’ll check to make sure it exists, and log an error if it doesn’t.

In our Awake method, we’ll set out static _instance variable to this instance of GameManager.

Now we’ll create another property; a bool named HasCard. This property’s get and set are both public and can be used by other classes. This way we don’t have to get a handle to the GameManager from each class that wants to access it.

We have a trigger collider in our scene that will play the cutscene of our player taking the keycard from the sleeping guard. In the OnTriggerEnter method, if the player is the one triggering the collision, AND the GameManager Instance’s HasCard property is false, the method will set the GameManager Instance’s HasCard property to true and activate the grab key cutscene.

Now that the HasCard property is true, further triggers will be ignored.

Using a singleton game manager like this would also be a good way to keep track of the player’s score.

Do keep in mind that properties are not viewable in the Inspector, but they can be viewed in Debug mode.

We can’t see the “HasCard” property in the Inspector…
…but we can in Debug mode.

--

--

Ryan Sweigart
Ryan Sweigart

Written by Ryan Sweigart

An independent Unity Developer.

No responses yet