Skip to content

Singleton

The Singleton pattern ensures there's, at most, one instance of a class at any given time. Because of that, it can be globally accessed from its class name. To make a singleton class, inherit from the Singleton<T> type:

public MyClass : Singleton<MyClass>
{ }

To access this class, use MyClass.Instance which returns an instance of the MyClass. If none was present, it creates one and then it returns it, so you don't have to worry about keeping track whether it has been created or not.

MonoBehaviour

This Singleton pattern is specifically designed to work with Unity and thus, it requires the MyClass to inherit from MonoBehaviour. However, this is defined automatically when inheriting from the Singleton<T> class.

If you need to perform some setup when creating a new class instance, override the the OnCreate() method. Likewise, you can also override the OnDestroy() method to execute some logic when the instance is destroyed.

public MyClass : Singleton<MyClass>
{ 
    protected override void OnCreate()
    {
        base.OnCreate();
        // This is executed only once when created
    }

    protected override void OnDestroy()
    {
        base.OnDestroy();
        // This is executed only once when destroyed
    }
}

Singleton instances can survive or be destroyed every time their scene is unloaded. By default all singleton classes survivde scene reloading. But if you want to destroy them when changing between scenes, override the SurviveSceneLoads and set it to false:

public MyClass : Singleton<MyClass>
{ 
    protected override bool SurviveSceneLoads => false;
}