Singleton`1.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using UnityEngine;
  3. namespace HeurekaGames
  4. {
  5. public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
  6. {
  7. public static T Instance
  8. {
  9. get
  10. {
  11. if (Singleton<T>.applicationIsQuitting)
  12. {
  13. UnityEngine.Debug.LogWarning("[Singleton] Instance '" + typeof(T) + "' already destroyed on application quit. Won't create again - returning null.");
  14. return (T)((object)null);
  15. }
  16. object @lock = Singleton<T>._lock;
  17. T instance;
  18. lock (@lock)
  19. {
  20. if (Singleton<T>._instance == null)
  21. {
  22. Singleton<T>._instance = (T)((object)UnityEngine.Object.FindObjectOfType(typeof(T)));
  23. if (UnityEngine.Object.FindObjectsOfType(typeof(T)).Length > 1)
  24. {
  25. UnityEngine.Debug.LogError("[Singleton] Something went really wrong - there should never be more than 1 singleton! Reopenning the scene might fix it.");
  26. return Singleton<T>._instance;
  27. }
  28. if (Singleton<T>._instance == null)
  29. {
  30. GameObject gameObject = new GameObject();
  31. Singleton<T>._instance = gameObject.AddComponent<T>();
  32. gameObject.name = "(singleton) " + typeof(T).ToString();
  33. UnityEngine.Debug.Log("[Singleton] An instance of " + typeof(T) + " was created.");
  34. }
  35. else
  36. {
  37. UnityEngine.Debug.Log("[Singleton] Using instance already created: " + Singleton<T>._instance.gameObject.name);
  38. }
  39. }
  40. instance = Singleton<T>._instance;
  41. }
  42. return instance;
  43. }
  44. }
  45. public void OnDestroy()
  46. {
  47. Singleton<T>.applicationIsQuitting = true;
  48. }
  49. private static T _instance;
  50. private static object _lock = new object();
  51. private static bool applicationIsQuitting = false;
  52. }
  53. }