The Singleton
When we started the development of our game, we managed all our objects locally within the scene. We didn't want or need to worry about the lifetime of our services/managers. However, as almost always is the case, our game matured, and we started using multiple scenes. Now, we needed our services or manager classes to be easily accessible by child scenes and almost anywhere in our code.
In games of old, we would have just created a global or static variable to track game state across scenes or scripts. A global static class could work, but suffers from a number of limitations, as follows:
- Static classes are lazy loaded and can be especially fragile in Unity.
- Static classes cannot implement an interface.
- Static classes can only be derived from an object. They cannot inherit from
MonoBehaviour
and thus be used as components in Unity, which means that they cannot also use Unity Coroutines or other base methods, such asStart
,Update
, and so on.
Let's take a look at the difference in...