Singletons in Game Development
This article is going to be a quick look at Singletons and their uses in Game Development. A Singleton is a class that only allows a single instance of itself to be created and gives simple access. That is the Singleton Design Pattern and is one of the most well-known patterns.
Singletons are used for classes that do not need to be copied multiple times during a game. In Game Development, they are most commonly used for manager classes like Game Manager or Audio Manager, which there will ever only be one in a scene.
Singletons are very powerful, but with that power comes danger. The danger of Singletons is that if not used correctly, they can cause errors in your program when there is more than one instance of a class in the scene. To use Singletons safely, you need to have a private and public static Instance of the Singleton. The public Instance returns the private instance. If the private instance is null, it searches the scene for a Singleton and makes that the private instance.
The Mono Singleton is a generic Singleton class that scripts can inherit from making them Singletons. The class takes a generic Type ‘ T ’ parameter, where ‘ T ‘ is the class that is inheriting from the Mono Singleton.
To make another script a Singleton, you inherit from the Mono Singleton and pass in the script’s class.