Skip to main content

Mono Singletons

Mono Singletons are monobehaviours of which only one can be present at the same time. They can easily be referenced using the INSTANCE property. They are ideal for manager classes such as a Game Manager, Audio Manager, etc... When there is no instance present in the scene, one will be created when you try to use the singleton. In most cases you don't want to add the script to a GameObject in your scene.

Creating a Singleton

To create a singleton, all you have to do is inherit from Monosingleton.

using ExtensionTools.Singleton;
public class MyCustomSingleton : MonoSingleton<MyCustomSingleton>
{
public void LogTest()
{
Debug.Log("I am a singleton");
}
}

Now we have a singleton and we can easily call the LogTest method from anywhere without having to keep a reference.

MyCustomSingleton.INSTANCE.LogTest(); 

Making the Singleton persistent across scenes

Sometimes singletons shouldn't be created foreach scene. We might want to have one persistent reference to the same singleton across all scenes. For example an Audio Manager, it doesn't make sense to have one for every scene since audio will be handled the same in every scene.

To keep singletons persistent across scenes we just have to set the DontDestroyOnLoad boolean to true in the constructor.

using ExtensionTools.Singleton;
public class MyCustomSingleton : MonoSingleton<MyCustomSingleton>
{
public MyCustomSingleton() : base(true)
{
}

public void LogTest()
{
Debug.Log("I am a singleton");
}
}