SRAutoSingleton`1.cs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using System;
  2. using System.Diagnostics;
  3. using UnityEngine;
  4. namespace SRF.Components
  5. {
  6. public abstract class SRAutoSingleton<T> : SRMonoBehaviour where T : SRAutoSingleton<T>
  7. {
  8. public static T Instance
  9. {
  10. [DebuggerStepThrough]
  11. get
  12. {
  13. if (SRAutoSingleton<T>._instance == null && Application.isPlaying)
  14. {
  15. GameObject gameObject = new GameObject("_" + typeof(T).Name);
  16. gameObject.AddComponent<T>();
  17. }
  18. return SRAutoSingleton<T>._instance;
  19. }
  20. }
  21. public static bool HasInstance
  22. {
  23. get
  24. {
  25. return SRAutoSingleton<T>._instance != null;
  26. }
  27. }
  28. protected virtual void Awake()
  29. {
  30. if (SRAutoSingleton<T>._instance != null)
  31. {
  32. UnityEngine.Debug.LogWarning("More than one singleton object of type {0} exists.".Fmt(new object[]
  33. {
  34. typeof(T).Name
  35. }));
  36. return;
  37. }
  38. SRAutoSingleton<T>._instance = (T)((object)this);
  39. }
  40. private void OnApplicationQuit()
  41. {
  42. SRAutoSingleton<T>._instance = (T)((object)null);
  43. }
  44. private static T _instance;
  45. }
  46. }