mbonatsos
3/9/2019 - 6:38 PM

MonoBehaviourSingleton.cs

using UnityEngine;

/// <summary>
/// Ensures that there will be only one instance of <typeparamref name="T"/> active on any scene.
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class MonoBehaviourSingleton<T> : MonoBehaviour where T : class
{
    private static T _instance = null;

    private void Awake()
    {
        if (_instance == null)
        {
            _instance = this as T;
            DontDestroyOnLoad(this);
            Initialize();
        }
        else if (_instance.GetHashCode() != this.GetHashCode())
        {
            DestroyImmediate(this.gameObject);
        }
    }

    protected virtual void Initialize() { }
}