SRScriptRecompileHelper.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #if UNITY_EDITOR
  2. using UnityEngine;
  3. namespace SRDebugger.Scripts.Internal
  4. {
  5. /// <summary>
  6. /// Behaviour that supports SRDebugger reloading itself after a script recompile is detected.
  7. /// </summary>
  8. public class SRScriptRecompileHelper : MonoBehaviour
  9. {
  10. private static SRScriptRecompileHelper _instance;
  11. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
  12. public static void Initialize()
  13. {
  14. if (_instance != null)
  15. {
  16. return;
  17. }
  18. var go = new GameObject("SRDebugger Script Recompile Helper (Editor Only)");
  19. DontDestroyOnLoad(go);
  20. go.hideFlags = HideFlags.DontSave | HideFlags.HideInHierarchy;
  21. go.AddComponent<SRScriptRecompileHelper>();
  22. }
  23. private bool _hasEnabled;
  24. private bool _srdebuggerHasInitialized;
  25. void OnEnable()
  26. {
  27. if(_instance != null)
  28. {
  29. Destroy(gameObject);
  30. return;
  31. }
  32. _instance = this;
  33. // Don't take any action on the first OnEnable()
  34. if (!_hasEnabled)
  35. {
  36. _hasEnabled = true;
  37. return;
  38. }
  39. // Next OnEnable() will be due to script reload.
  40. AutoInitialize.OnLoadBeforeScene();
  41. if (_srdebuggerHasInitialized)
  42. {
  43. Debug.Log("[SRScriptRecompileHelper] Restoring SRDebugger after script reload.", this);
  44. SRDebug.Init();
  45. }
  46. }
  47. void OnApplicationQuit()
  48. {
  49. // Destroy this object when leaving play mode (otherwise it will linger and a new instance will be created next time play mode is entered).
  50. Destroy(gameObject);
  51. }
  52. public static void SetHasInitialized()
  53. {
  54. if (_instance == null)
  55. {
  56. Initialize();
  57. }
  58. _instance._srdebuggerHasInitialized = true;
  59. }
  60. }
  61. }
  62. #endif