Much like the Highlander as with Singletons there can only be one. So controversial are singletons that they’re often considered an anti-pattern by some software developers. So what is a Singleton really? They are defined simply as “ensures only one instance of a class is instantiated for the life of the application.” what this really means is that there is only ever one of that class. This can be for example such an Audio Manager, Game Manager, High Score Manager, etc. The reason they continue to persist is that they’re easy, the ability to call the singleton from any part of the project is deeply appealing. It also centralizes the logic of the project around a few key managers making it easy to access that data.
Naturally the very reasons they’re touted is the reason they’re vilified. When you centralize your code you by it’s very design, tightly couple it. So your physics code now ties into your particle effects code which then ties into your score managing code. This creates a situation where it is more difficult to reason the code you’ve created because it spiders into other scripts. Which then potentially creates hard to track/trace race conditions, synchronization issues, and deadlocks. It can get messy fast but if used sparingly (and I mean really sparingly) singletons can be real life savers and ultimately useful not the ticking timebombs in your codebase people like to call them. So how do you make a singleton? Let’s take a look.
The process is fairly straight forward, there’s a bit more complexity such as setting up the Getter to make another Game Object if the singleton isn’t present. Then checking again in Awake() that it’s null otherwise destroying any other instance. The most important addition is the inclusion of DontDestroyOnLoad() which gives the singleton persistence. You can read more about DontDestroyOnLoad() here but essentially it tells Unity not to clean up the Game Manager when a new scene loads. This extends the usefulness of the singleton by making it the only one of it’s kind during the life of the game.
Typically for a singleton (or two) you would initialize them during your initial loading screen/splash screen before your main menu or game start so that they can be the only possible singleton(s) created. There you can carry them forward throughout the life of your game until the player quits, the game crashes (which should never happen), or the power gets pulled. Until next time, happy coding.