MonoSingleton.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using UnityEngine;
  3. public class MonoSingleton<T> : MonoBehaviour where T : Component
  4. {
  5. private static T _instance;
  6. public static T Instance
  7. {
  8. get
  9. {
  10. if (_instance == null)
  11. {
  12. CreateInstance();
  13. }
  14. return _instance;
  15. }
  16. }
  17. private static void CreateInstance()
  18. {
  19. Type theType = typeof(T);
  20. _instance = (T)FindObjectOfType(theType);
  21. if (_instance == null)
  22. {
  23. var go = new GameObject(typeof(T).Name);
  24. _instance = go.AddComponent<T>();
  25. GameObject rootObj = GameObject.Find("TapSDKSingletons");
  26. if (rootObj == null)
  27. {
  28. rootObj = new GameObject("TapSDKSingletons");
  29. DontDestroyOnLoad(rootObj);
  30. }
  31. go.transform.SetParent(rootObj.transform);
  32. }
  33. }
  34. public static void DestroyInstance()
  35. {
  36. if (_instance != null)
  37. {
  38. Destroy(_instance.gameObject);
  39. }
  40. }
  41. public static bool HasInstance()
  42. {
  43. return _instance != null;
  44. }
  45. protected virtual void Awake()
  46. {
  47. if (_instance != null && _instance.gameObject != gameObject)
  48. {
  49. if (Application.isPlaying)
  50. {
  51. Destroy(gameObject);
  52. }
  53. else
  54. {
  55. DestroyImmediate(gameObject); // UNITY_EDITOR
  56. }
  57. return;
  58. }
  59. else if (_instance == null)
  60. {
  61. _instance = GetComponent<T>();
  62. }
  63. DontDestroyOnLoad(gameObject);
  64. Init();
  65. }
  66. protected virtual void OnDestroy()
  67. {
  68. Uninit();
  69. if (_instance != null && _instance.gameObject == gameObject)
  70. {
  71. _instance = null;
  72. }
  73. }
  74. protected virtual void Init() {}
  75. public virtual void Uninit() {}
  76. }