Singleton.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using UnityEngine;
  2. // ReSharper disable StaticMemberInGenericType
  3. // ReSharper disable InconsistentNaming
  4. namespace ARLocation.Utils
  5. {
  6. public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
  7. {
  8. // Check to see if we're about to be destroyed.
  9. private static bool m_ShuttingDown;
  10. private static object m_Lock = new object();
  11. private static T m_Instance;
  12. /// <summary>
  13. /// Access singleton instance through this propriety.
  14. /// </summary>
  15. public static T Instance
  16. {
  17. get
  18. {
  19. if (m_ShuttingDown)
  20. {
  21. Debug.LogWarning("[Singleton] Instance '" + typeof(T) +
  22. "' already destroyed. Returning null.");
  23. return null;
  24. }
  25. lock (m_Lock)
  26. {
  27. if (m_Instance == null)
  28. {
  29. // Search for existing instance.
  30. m_Instance = (T)FindObjectOfType(typeof(T));
  31. // Create new instance if one doesn't already exist.
  32. if (m_Instance == null)
  33. {
  34. // Need to create a new GameObject to attach the singleton to.
  35. var singletonObject = new GameObject();
  36. m_Instance = singletonObject.AddComponent<T>();
  37. singletonObject.name = typeof(T) + " (Singleton)";
  38. // Make instance persistent.
  39. DontDestroyOnLoad(singletonObject);
  40. }
  41. }
  42. return m_Instance;
  43. }
  44. }
  45. }
  46. public virtual void Awake()
  47. {
  48. m_ShuttingDown = false;
  49. }
  50. private void OnApplicationQuit()
  51. {
  52. m_ShuttingDown = true;
  53. }
  54. private void OnDestroy()
  55. {
  56. m_ShuttingDown = true;
  57. }
  58. }
  59. }