MonoSingleton.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using UnityEngine;
  3. namespace Rokid.UXR
  4. {
  5. /// <summary>
  6. /// Mono Singleton
  7. /// </summary>
  8. public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
  9. {
  10. private static T m_Instance;
  11. /// <summary>
  12. /// Singleton Object
  13. /// </summary>
  14. public static T Instance
  15. {
  16. get
  17. {
  18. if (m_Instance == null)
  19. {
  20. T[] ts = GameObject.FindObjectsOfType<T>();
  21. if (ts != null && ts.Length > 0)
  22. {
  23. if (ts.Length == 1)
  24. {
  25. m_Instance = ts[0];
  26. }
  27. else
  28. {
  29. throw new Exception(string.Format("## Uni Exception ## Cls:{0} Info:Singleton not allows more than one instance", typeof(T)));
  30. }
  31. }
  32. else
  33. {
  34. m_Instance = new GameObject(string.Format("{0}(Singleton)", typeof(T).ToString())).AddComponent<T>();
  35. m_Instance.OnSingletonInit();
  36. }
  37. }
  38. return m_Instance;
  39. }
  40. }
  41. protected MonoSingleton() { }
  42. protected virtual void Awake()
  43. {
  44. m_Instance = this as T;
  45. }
  46. protected virtual void OnDestroy()
  47. {
  48. }
  49. protected virtual void OnSingletonInit()
  50. {
  51. }
  52. }
  53. }