Unity---singleton class

using UnityEngine;

public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    public static T Instance
    {
        get
        {
            if (appIsClosing)
            {
                return (T)((object)null);
            }
            if (_instance == null)
            {
                T[] array = FindObjectsOfType<T>();
                if (array.Length > 0)
                {
                    _instance = array[0];
                }
                if (array.Length > 1)
                {
                    Debug.LogError("There is more than one " + typeof(T).Name + " in the scene.");
                }
                if (_instance == null)
                {
                    string name = typeof(T).ToString();
                    GameObject gameObject = GameObject.Find(name);
                    if (gameObject == null)
                    {
                        gameObject = new GameObject(name);
                    }
                    _instance = gameObject.AddComponent<T>();
                }
            }
            return _instance;
        }
    }

    protected virtual void OnApplicationQuit()
    {
        appIsClosing = true;
    }

    protected virtual void Awake()
    {
        DontDestroyOnLoad(this);
    }

    private static T _instance;

    private static bool appIsClosing;
}

Guess you like

Origin blog.csdn.net/lalate/article/details/130266863