Game Programming Pattern: Singleton

What’s the best thing about singleton patterns? Is it the way they make you sound cool, professional, and authoritative with your non-programming friends and family? I mean, yeah, there’s that, but when you’re programming in Unity, Singletons make things so much easier when you need to communicate amongst classes.

Normally, you'd have to get a handle on another class, stick a GetComponent on it, tell it again what you’re trying to access, and then actually do something productive. It’s akin to needing to press a bunch of the whole bunch of bicycle captcha photos before posting a message. Annoying, but it needs to be done if you want to get your message across.


Enter the singleton pattern! With a few lines of code, your class will be available directly with no middleman!
A few caveats. You shouldn’t use singletons for everything, as tempting as it is. A general rule of thumb is if there’s only going to be one of something in your game like a GameManager, Audio Manager, UI Manager, etc. You can make it a singleton.
Let’s say we’ve just started a new game manager.

The first thing we need is to make the GameManager static, when something is static, it becomes available to all the classes in the game at all times during run-time.

But wait…you just made it private! A private variable isn’t available to everyone! Yes, that’s true! We only want this instance..or _instance of the Gamemanager to be available only to itself. It’s precious. It needs protection. And that’s why we have:

We still have our game manager class available to all through the public Instance! Think of this as the firewall for our _instance. Notice there are also brackets, we’re going to be putting some things in our Instance in a moment!

A getter will give another class information, and in our case, we’re checking to see if _instance actually exists before returning it. A setter will allow another class to change information.
You know what. We don’t want a setter here. It’s best to keep the class available for reading and not major modification so we’ll delete it since it kind of defeats the purpose of our firewall.

Much better! This is just one half of the pattern, there’s still one vital element left and that’s saying that the variable of type GameManager is this in the classes Awake function:

This completes the circle and now, you can access the Gamemanager anywhere! With a little bit of practice, this pattern will become not only second nature but an oft-used tool in your growing library of programming prowess!
Tomorrow, we’ll talk about making loading scenes in Unity!