U_单例 Singleton

using UnityEngine;
namespace LazyPan.Tool {
    public class Singleton<T> : MonoBehaviour where T : MonoBehaviour {
        static T instance = null;

        public static T Instance {
            get {
                if (instance != null) {
                    return instance;
                }

                instance = new GameObject(typeof(T).Name).AddComponent<T>();
                if (Application.isPlaying) {
                    DontDestroyOnLoad(instance.gameObject);
                }

                return instance;
            }
        }

        private void Awake() {
            instance = this as T;
        }
    }
}
posted @ 2023-11-08 14:33  匿鱼  阅读(14)  评论(0)    收藏  举报