SingleTon和MonoSingeTon通用单例模板类

    xiaoxiao2022-07-13  149

    SingleTon:

    public class SingleTon<T> where T : new() { private static T _instance; private static T Instance { get { if (_instance == null) _instance = new T(); return _instance; } } }

    MonoSingleTon:

    public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>{ private static T m_Instance = null; public static T instance{ get{ if( m_Instance == null ) { m_Instance = GameObject.FindObjectOfType(typeof(T)) as T; if( m_Instance == null ) { GameObject go = new GameObject(typeof(T).ToString()); m_Instance = go.AddComponent<T>(); m_Instance.Init(); } } return m_Instance; } } public virtual void Init(){ } private void OnApplicationQuit(){ m_Instance = null; } }

     

    最新回复(0)