123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- using UnityEngine;
- namespace Plugins.CxShine.Singleton
- {
- public class UnitySingleton<T> : MonoBehaviour
- where T : Component
- {
- private static T _instance;
- public static T Instance
- {
- get
- {
- if (_instance == null)
- {
- // 利用反射创建 Unity 物体
- _instance = FindObjectOfType(typeof(T)) as T;
- if (_instance == null)
- {
- var obj = new GameObject();
- // 利用反射创建 Unity 组件
- _instance = obj.AddComponent(typeof(T)) as T;
- }
- }
- return _instance;
- }
- }
- public virtual void Awake()
- {
- DontDestroyOnLoad(gameObject);
- if (_instance == null)
- _instance = this as T;
- else
- {
- Destroy(gameObject);
- }
- }
- public static void RemoveTransformAllChild(Transform tr)
- {
- for (int i = 0; i < tr.childCount; i++)
- {
- tr.GetChild(i).gameObject.SetActive(false);
- Destroy(tr.GetChild(i).gameObject);
- }
- }
- }
- }
|