SingletonMono.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using UnityEngine;
  2. using System.Collections;
  3. public class MonoBase : MonoBehaviour
  4. {
  5. }
  6. public class SingletonMono<T> : MonoBase where T : MonoBase
  7. {
  8. private static T instance;
  9. public static T Instance
  10. {
  11. get
  12. {
  13. if (instance != null)
  14. {
  15. #if UNITY_EDITOR
  16. if (applicationIsQuitting)
  17. {
  18. DebugHelper.Log("[Singleton] Instance [ {0} ] already destroyed on application quit. Won't create again - returning null.", typeof(T));
  19. return null;
  20. }
  21. #endif
  22. return instance;
  23. }
  24. #if UNITY_EDITOR
  25. if (!Application.isPlaying)
  26. {
  27. GameObject singleton = GameObject.Find("Editor");
  28. if (singleton == null)
  29. singleton = new GameObject("Editor");
  30. instance = singleton.transform.GetOrAddComponent<T>();
  31. return instance;
  32. }
  33. else
  34. {
  35. if (applicationIsQuitting)
  36. {
  37. DebugHelper.Log("[Singleton] Instance [ {0} ] already destroyed on application quit. Won't create again - returning null.", typeof(T));
  38. return null;
  39. }
  40. GameObject go = new GameObject(typeof(T).Name);
  41. instance = go.AddComponent<T>();
  42. DontDestroyOnLoad(go);
  43. return instance;
  44. }
  45. #else
  46. if (GameMgr.Instance != null)
  47. {
  48. if (typeof(T).Equals(typeof(UIMgr)))
  49. {
  50. GameObject singleton = new GameObject(typeof(T).ToString());
  51. singleton.transform.parent = GameMgr.Instance.transform;
  52. instance = singleton.AddComponent<T>();
  53. }
  54. else
  55. instance = GameMgr.Instance.GetOrAddComponent<T>();
  56. }
  57. else if (GameMgr.Instance == null)
  58. {
  59. GameObject singleton = new GameObject(typeof(T).ToString());
  60. instance = singleton.AddComponent<T>();
  61. }
  62. return instance;
  63. #endif
  64. }
  65. }
  66. private static bool applicationIsQuitting = false;
  67. protected void OnDestroy()
  68. {
  69. Dispose();
  70. }
  71. public virtual void InitMgr()
  72. {
  73. }
  74. protected virtual void Dispose()
  75. {
  76. instance = null;
  77. }
  78. protected virtual void OnApplicationQuit()
  79. {
  80. applicationIsQuitting = true;
  81. instance = null;
  82. }
  83. public static bool HasInstance()
  84. {
  85. return (instance != null);
  86. }
  87. }