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 class 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.

Edit mode

The Instance property always returns null when the game is not running (in the Editor's edit mode), as singletons are only created at runtime.

If you need to perform some setup when creating a new class instance, override the OnCreate() method:

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

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

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