FirebaseManager.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using UnityEngine;
  2. namespace SimpleFirebaseUnity
  3. {
  4. [ExecuteInEditMode]
  5. public class FirebaseManager : MonoBehaviour
  6. {
  7. private static FirebaseManager _instance;
  8. private static object _lock = new object();
  9. protected FirebaseManager() { }
  10. public static FirebaseManager Instance
  11. {
  12. get
  13. {
  14. if (applicationIsQuitting)
  15. {
  16. Debug.LogWarning("[Firebase Manager] Instance already destroyed on application quit." +
  17. " Won't create again - returning null.");
  18. return null;
  19. }
  20. lock (_lock)
  21. {
  22. if (_instance == null)
  23. {
  24. FirebaseManager[] managers = FindObjectsOfType<FirebaseManager>();
  25. _instance = (managers.Length > 0) ? managers[0] : null;
  26. if (managers.Length > 1)
  27. {
  28. Debug.LogError("[Firebase Manager] Something went really wrong " +
  29. " - there should never be more than 1 Firebase Manager!" +
  30. " Reopening the scene might fix it.");
  31. return _instance;
  32. }
  33. if (_instance == null)
  34. {
  35. GameObject singleton = new GameObject();
  36. _instance = singleton.AddComponent<FirebaseManager>();
  37. singleton.name = "Firebase Manager [Singleton]";
  38. DontDestroyOnLoad(singleton);
  39. Debug.Log("[Firebase Manager] Instance '" + singleton +
  40. "' was generated in the scene with DontDestroyOnLoad.");
  41. }
  42. else {
  43. Debug.Log("[Firebase Manager] Using instance already created: " +
  44. _instance.gameObject.name);
  45. }
  46. }
  47. return _instance;
  48. }
  49. }
  50. }
  51. private static bool applicationIsQuitting = false;
  52. /// <summary>
  53. /// When Unity quits, it destroys objects in a random order.
  54. /// In principle, a Singleton is only destroyed when application quits.
  55. /// If any script calls Instance after it have been destroyed,
  56. /// it will create a buggy ghost object that will stay on the Editor scene
  57. /// even after stopping playing the Application. Really bad!
  58. /// So, this was made to be sure we're not creating that buggy ghost object.
  59. /// </summary>
  60. public void OnDestroy()
  61. {
  62. if (Application.isPlaying)
  63. applicationIsQuitting = true;
  64. }
  65. }
  66. }