Unity Development — Singleton Pattern

Christopher Graf
3 min readJul 21, 2021

The Singleton Pattern allows us to make an instance that can be accessed from anywhere. While not specific to game development, that is certainly the type of example we are going to use.

Since this pattern allows access from anywhere, it is often used for a manager class. In our example, we are going to create a GameManager script. You could also create an empty Game Manager object to place the script on.

First, at the top of the script where you would normally declare the variables, you are going to make a private static instance. The type is going to be the very name of the class. That is because you are quite literally creating an instance of this very class.

This part of the instance is private, so we need something else that allows access for everyone else. Again, we are going to declare an instance, but the naming convention is now capital and it will be public.

This new Instance is going to get the original private one, checking that it exists, and then return it.

Then in the Awake() method, we are going to declare this instance to the very class we are in.

After this is complete, we can now use the public Instance to have complete access to this class. Let’s say we had an in game currency that the game manager was in charge of handling. If our character picked up some coins or some other form of money, we can call on the GameManager very easily.

In the GameManager we can create a public method to do whatever we like. In this case, it updates the currency by adding in an amount, taking an int as a parameter. When we want to call this method, we just need the class and Instance.

Place this on any script in the project and it will have access. Try some other ideas out for yourself. With full access to a manager, many doors will now be opened to you.

--

--