MonoSingleton.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using UnityEngine;
  3. public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
  4. {
  5. private static T instance
  6. {
  7. get
  8. {
  9. if (MonoSingleton<T>.m_Instance != null)
  10. {
  11. return MonoSingleton<T>.m_Instance;
  12. }
  13. Type typeFromHandle = typeof(T);
  14. T t = UnityEngine.Object.FindObjectOfType(typeFromHandle) as T;
  15. if (t == null)
  16. {
  17. string text = typeFromHandle.ToString();
  18. GameObject gameObject = new GameObject(text, new Type[]
  19. {
  20. typeFromHandle
  21. });
  22. t = gameObject.GetComponent<T>();
  23. if (t == null)
  24. {
  25. Debug.LogError("Problem during the creation of " + text, gameObject);
  26. }
  27. }
  28. else
  29. {
  30. MonoSingleton<T>.Initialize(t);
  31. }
  32. return MonoSingleton<T>.m_Instance;
  33. }
  34. }
  35. private static void Initialize(T instance)
  36. {
  37. if (MonoSingleton<T>.m_Instance == null)
  38. {
  39. MonoSingleton<T>.m_Instance = instance;
  40. MonoSingleton<T>.m_Instance.OnInitialize();
  41. }
  42. else if (MonoSingleton<T>.m_Instance != instance)
  43. {
  44. UnityEngine.Object.DestroyImmediate(instance.gameObject);
  45. }
  46. }
  47. private static void Destroyed(T instance)
  48. {
  49. if (MonoSingleton<T>.m_Instance == instance)
  50. {
  51. MonoSingleton<T>.m_Instance.OnFinalize();
  52. MonoSingleton<T>.m_Instance = (T)((object)null);
  53. }
  54. }
  55. public virtual void OnInitialize()
  56. {
  57. }
  58. public virtual void OnFinalize()
  59. {
  60. }
  61. private void Awake()
  62. {
  63. UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
  64. MonoSingleton<T>.Initialize(this as T);
  65. }
  66. private void OnDestroy()
  67. {
  68. MonoSingleton<T>.Destroyed(this as T);
  69. }
  70. protected virtual void OnApplicationQuit()
  71. {
  72. MonoSingleton<T>.Destroyed(this as T);
  73. }
  74. private static T m_Instance;
  75. }