unity3dSingletons in Unity


Remarks

While there are schools of thought which make compelling arguments why unconstrained use of Singletons is a bad idea, e.g. Singleton on gameprogrammingpatterns.com, there are occasions when you might want to persist a GameObject in Unity over multiple Scenes (e.g. for seamless background music) while ensuring that no more than one instance can exist; a perfect use case for a Singleton.

By adding this script to a GameObject, once it has been instantiated (e.g. by including it anywhere in a Scene) it will remain active across Scenes, and only one instance will ever exist.


ScriptableObject (UnityDoc) instances provide a valid alternative to Singletons for some use cases. While they don't implicitly enforce the single instance rule, they retain their state between scenes and play nicely with the Unity serialization process. They also promote Inversion of Control as dependencies are injected through the editor.

// MyAudioManager.cs
using UnityEngine;

[CreateAssetMenu] // Remember to create the instance in editor
public class MyAudioManager : ScriptableObject {
    public void PlaySound() {}
}
// MyGameObject.cs
using UnityEngine;

public class MyGameObject : MonoBehaviour
{
    [SerializeField]
    MyAudioManager audioManager; //Insert through Inspector

    void OnEnable()
    {
        audioManager.PlaySound();
    }
}

Further reading