2021년 4학년 1학기 기업연계프로젝트2 컴퓨터소프트웨어공학과 <원광투어팀> 팀장 : 송유진 팀원 : 김나영, 이경희, 한유진
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

92 lines
2.8 KiB

5 years ago
  1. //========= Copyright 2016-2020, HTC Corporation. All rights reserved. ===========
  2. using System;
  3. using UnityEngine;
  4. namespace HTC.UnityPlugin.Utility
  5. {
  6. [DisallowMultipleComponent]
  7. public abstract class SingletonBehaviour<T> : MonoBehaviour where T : SingletonBehaviour<T>
  8. {
  9. private static T s_instance = null;
  10. private static bool s_isApplicationQuitting = false;
  11. private static object s_lock = new object();
  12. private static Func<GameObject> s_defaultInitGOGetter;
  13. private bool m_initialized;
  14. public static bool Active { get { return !s_isApplicationQuitting && s_instance != null; } }
  15. public bool IsInstance { get { return this == Instance; } }
  16. protected bool IsApplicationQuitting { get { return s_isApplicationQuitting; } }
  17. public static T Instance
  18. {
  19. get
  20. {
  21. Initialize();
  22. return s_instance;
  23. }
  24. }
  25. public static void Initialize()
  26. {
  27. if (!Application.isPlaying || s_isApplicationQuitting) { return; }
  28. lock (s_lock)
  29. {
  30. if (s_instance != null) { return; }
  31. var instances = FindObjectsOfType<T>();
  32. if (instances.Length > 0)
  33. {
  34. s_instance = instances[0];
  35. if (instances.Length > 1) { Debug.LogWarning("Multiple " + typeof(T).Name + " not supported!"); }
  36. }
  37. if (s_instance == null)
  38. {
  39. GameObject defaultInitGO = null;
  40. if (s_defaultInitGOGetter != null)
  41. {
  42. defaultInitGO = s_defaultInitGOGetter();
  43. }
  44. if (defaultInitGO == null)
  45. {
  46. defaultInitGO = new GameObject("[" + typeof(T).Name + "]");
  47. }
  48. s_instance = defaultInitGO.AddComponent<T>();
  49. }
  50. if (!s_instance.m_initialized)
  51. {
  52. s_instance.m_initialized = true;
  53. s_instance.OnSingletonBehaviourInitialized();
  54. }
  55. }
  56. }
  57. /// <summary>
  58. /// Must set before the instance being initialized
  59. /// </summary>
  60. public static void SetDefaultInitGameObjectGetter(Func<GameObject> getter) { s_defaultInitGOGetter = getter; }
  61. protected virtual void OnSingletonBehaviourInitialized() { }
  62. protected virtual void OnApplicationQuit()
  63. {
  64. s_isApplicationQuitting = true;
  65. }
  66. protected virtual void OnDestroy()
  67. {
  68. if (!s_isApplicationQuitting && s_instance == this)
  69. {
  70. s_instance = null;
  71. }
  72. }
  73. }
  74. }