SRSingleton`1.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.Diagnostics;
  3. using UnityEngine;
  4. namespace SRF.Components
  5. {
  6. public abstract class SRSingleton<T> : SRMonoBehaviour where T : SRSingleton<T>
  7. {
  8. public static T Instance
  9. {
  10. [DebuggerStepThrough]
  11. get
  12. {
  13. if (SRSingleton<T>._instance == null)
  14. {
  15. throw new InvalidOperationException("No instance of {0} present in scene".Fmt(new object[]
  16. {
  17. typeof(T).Name
  18. }));
  19. }
  20. return SRSingleton<T>._instance;
  21. }
  22. }
  23. public static bool HasInstance
  24. {
  25. [DebuggerStepThrough]
  26. get
  27. {
  28. return SRSingleton<T>._instance != null;
  29. }
  30. }
  31. private void Register()
  32. {
  33. if (SRSingleton<T>._instance != null)
  34. {
  35. UnityEngine.Debug.LogWarning("More than one singleton object of type {0} exists.".Fmt(new object[]
  36. {
  37. typeof(T).Name
  38. }));
  39. if (base.GetComponents<Component>().Length == 2)
  40. {
  41. UnityEngine.Object.Destroy(base.gameObject);
  42. }
  43. else
  44. {
  45. UnityEngine.Object.Destroy(this);
  46. }
  47. return;
  48. }
  49. SRSingleton<T>._instance = (T)((object)this);
  50. }
  51. protected virtual void Awake()
  52. {
  53. this.Register();
  54. }
  55. protected virtual void OnEnable()
  56. {
  57. if (SRSingleton<T>._instance == null)
  58. {
  59. this.Register();
  60. }
  61. }
  62. private void OnApplicationQuit()
  63. {
  64. SRSingleton<T>._instance = (T)((object)null);
  65. }
  66. private static T _instance;
  67. }
  68. }