Simple Generic Singleton

Generally I am not a big fan of having a ton of singletons in a project. Typically I will create some manager class that is a singleton then create references to scripts that other scripts need outside access to. (IE: PersistantObjects.Instance.LevelManager) But when I do end up having multiples, I typically make an abstract generic SingletonMonoBehaviour class:

using UnityEngine;

public abstract class SingletonMonoBehaviour<T> : MonoBehaviour where T : MonoBehaviour
{
    #region Properties:
    public static T Instance { get; private set; }
    #endregion

    #region MonoBehaviour Callback Method(s):
    protected virtual void Awake()
    {
        if (Instance != null)
        {
            Destroy(this);
            return;
        }

        Instance = this as T;
    }
    #endregion
}

Then to use:

public class SomeSingletonClass : SingletonMonoBehaviour<SomeSingletonClass>
{
    #region MonoBehaviour Callback Method(s):
    protected override void Awake()
    {
        // Make sure to call base.Awake() if you override the Awake() method:
        base.Awake();

        // Some additional logic for this class Awake:
    }
    #endregion
}

Hope this helps: Cheers

2 Likes

Yup if you have many singletons then that is a nice helper class.

2 Likes

Privacy & Terms