SRSingleton.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. namespace SRF.Components
  2. {
  3. using System;
  4. using System.Diagnostics;
  5. using UnityEngine;
  6. using Debug = UnityEngine.Debug;
  7. /// <summary>
  8. /// Inherit from this component to easily create a singleton gameobject.
  9. /// </summary>
  10. /// <typeparam name="T"></typeparam>
  11. public abstract class SRSingleton<T> : SRMonoBehaviour where T : SRSingleton<T>
  12. {
  13. private static T _instance;
  14. /// <summary>
  15. /// Get the instance of this singleton.
  16. /// </summary
  17. public static T Instance
  18. {
  19. [DebuggerStepThrough]
  20. get
  21. {
  22. // Instance requiered for the first time, we look for it
  23. if (_instance == null)
  24. {
  25. throw new InvalidOperationException("No instance of {0} present in scene".Fmt(typeof (T).Name));
  26. }
  27. return _instance;
  28. }
  29. }
  30. public static bool HasInstance
  31. {
  32. [DebuggerStepThrough] get { return _instance != null; }
  33. }
  34. private void Register()
  35. {
  36. if (_instance != null)
  37. {
  38. Debug.LogWarning("More than one singleton object of type {0} exists.".Fmt(typeof (T).Name));
  39. // Check if gameobject only contains Transform and this component
  40. if (GetComponents<Component>().Length == 2)
  41. {
  42. Destroy(gameObject);
  43. }
  44. else
  45. {
  46. Destroy(this);
  47. }
  48. return;
  49. }
  50. _instance = (T) this;
  51. }
  52. // If no other monobehaviour request the instance in an awake function
  53. // executing before this one, no need to search the object.
  54. protected virtual void Awake()
  55. {
  56. Register();
  57. }
  58. protected virtual void OnEnable()
  59. {
  60. // In case of code-reload, this should restore the single instance
  61. if (_instance == null)
  62. {
  63. Register();
  64. }
  65. }
  66. // Make sure the instance isn't referenced anymore when the user quit, just in case.
  67. private void OnApplicationQuit()
  68. {
  69. _instance = null;
  70. }
  71. }
  72. }