SingletonMono`1.cs 1022 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System;
  2. using UnityEngine;
  3. public class SingletonMono<T> : BaseBehaviour where T : MonoBehaviour
  4. {
  5. protected SingletonMono()
  6. {
  7. }
  8. public static T Instance
  9. {
  10. get
  11. {
  12. if (SingletonMono<T>.ApplicationIsQuitting)
  13. {
  14. UnityEngine.Debug.LogWarning("[Singleton] Instance '" + typeof(T) + "' already destroyed on application quit. Won't create again - returning null.");
  15. return (T)((object)null);
  16. }
  17. object @lock = SingletonMono<T>.Lock;
  18. lock (@lock)
  19. {
  20. if (SingletonMono<T>._instance == null)
  21. {
  22. SingletonMono<T>._instance = UnityEngine.Object.FindObjectOfType<T>();
  23. }
  24. }
  25. return SingletonMono<T>._instance;
  26. }
  27. }
  28. protected virtual void OnDestroy()
  29. {
  30. SingletonMono<T>.ApplicationIsQuitting = true;
  31. }
  32. public static bool IsValid()
  33. {
  34. return SingletonMono<T>._instance != null;
  35. }
  36. private static T _instance;
  37. private static readonly object Lock = new object();
  38. public static bool ApplicationIsQuitting = false;
  39. }