unity单例

泛型单例类

 public class Singleton<T> where T : new()
    {
        private static T instance;
        public static T Instacne
        {
            get
            {
                if (instance==null)
                {
                    instance = new T();
                }
                return instance;
            }
        }
    }

泛型单例脚本 

public class SingleMono<T> : MonoBehaviour where T : MonoBehaviour

    {
        private static T _instance;


        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    if (FindObjectsOfType(typeof(T)).Length > 1)
                    {
                        Debug.LogError("存在多个" + typeof(T).ToString() + "单例");
                        _instance = FindObjectOfType(typeof(T)) as T;
                    }
                    else if (FindObjectsOfType(typeof(T)).Length == 1)
                    {
                        _instance = FindObjectOfType(typeof(T)) as T;
                    }
                    else
                    {
                        GameObject Manager = GameObject.Find("Manager");


                        if (Manager == null)
                        {
                            Manager = new GameObject("Manager");
                        }


                        GameObject targetObj = new GameObject(typeof(T).ToString());
                        targetObj.transform.SetParent(Manager.transform);
                        targetObj.AddComponent<T>();
                        _instance = targetObj.GetComponent<T>();
                    }
                }
                else if (FindObjectsOfType(typeof(T)).Length > 1)
                {
                    Debug.LogError("存在多个" + typeof(T).ToString() + "单例");
                }
                return _instance;
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_35874030/article/details/80772766