随笔之制作单例

qq6322

1 回复15 浏览

来自课程:Steam模拟经营游戏《冒险村的商人日记》从开发到上架全流程

建议用泛型做单列,会省不少操作

    public class DDOLSingLeton<T> : MonoBehaviour where T : DDOLSingLeton<T>
    {
        protected static T _instance = null;

        public static T Inst
        {
            get
            {
                if (_instance == null)
                {
                    _instance = FindObjectOfType(typeof(T)) as T;
                    if (_instance != null)
                    {
                        return _instance;
                    }

                    GameObject go = GameObject.Find("DDOL");
                    if (go == null)
                    {
                        go = new GameObject("DDOL");
                        DontDestroyOnLoad(go);
                    }

                    _instance = go.GetComponent<T>();
                    if (_instance == null)
                    {
                        _instance = go.AddComponent<T>();
                    }
                }
                return _instance;
            }
        }
    }
    public class A : DDOLSingLeton<A>
    {
        public void Say(string str)
        {
            print(str);
        }
    }
    public class B : MonoBehaviour
    {
        // Start is called before the first frame update
        void Start()
        {
            A.Inst.Say("Hi!    Is a DDOLSingLeton");
        }
    }

全部回复(1)

发表回复

登录后可以回复