SingletonCrossSceneAutoCreate.cs 2.7 KB

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