UnitySingleton.cs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using UnityEngine;
  2. namespace Plugins.CxShine.Singleton
  3. {
  4. public class UnitySingleton<T> : MonoBehaviour
  5. where T : Component
  6. {
  7. private static T _instance;
  8. public static T Instance
  9. {
  10. get
  11. {
  12. if (_instance == null)
  13. {
  14. // 利用反射创建 Unity 物体
  15. _instance = FindObjectOfType(typeof(T)) as T;
  16. if (_instance == null)
  17. {
  18. var obj = new GameObject();
  19. // 利用反射创建 Unity 组件
  20. _instance = obj.AddComponent(typeof(T)) as T;
  21. }
  22. }
  23. return _instance;
  24. }
  25. }
  26. public virtual void Awake()
  27. {
  28. DontDestroyOnLoad(gameObject);
  29. if (_instance == null)
  30. _instance = this as T;
  31. else
  32. {
  33. Destroy(gameObject);
  34. }
  35. }
  36. public static void RemoveTransformAllChild(Transform tr)
  37. {
  38. for (int i = 0; i < tr.childCount; i++)
  39. {
  40. tr.GetChild(i).gameObject.SetActive(false);
  41. Destroy(tr.GetChild(i).gameObject);
  42. }
  43. }
  44. }
  45. }