ScenePlaybackDetector.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #if UNITY_EDITOR
  2. using UnityEditor;
  3. using UnityEditor.Callbacks;
  4. using UnityEngine;
  5. namespace UniRx
  6. {
  7. [InitializeOnLoad]
  8. public class ScenePlaybackDetector
  9. {
  10. private static bool _isPlaying = false;
  11. private static bool AboutToStartScene
  12. {
  13. get
  14. {
  15. return EditorPrefs.GetBool("AboutToStartScene");
  16. }
  17. set
  18. {
  19. EditorPrefs.SetBool("AboutToStartScene", value);
  20. }
  21. }
  22. public static bool IsPlaying
  23. {
  24. get
  25. {
  26. return _isPlaying;
  27. }
  28. set
  29. {
  30. if (_isPlaying != value)
  31. {
  32. _isPlaying = value;
  33. }
  34. }
  35. }
  36. // This callback is notified after scripts have been reloaded.
  37. [DidReloadScripts]
  38. public static void OnDidReloadScripts()
  39. {
  40. // Filter DidReloadScripts callbacks to the moment where playmodeState transitions into isPlaying.
  41. if (AboutToStartScene)
  42. {
  43. IsPlaying = true;
  44. }
  45. }
  46. // InitializeOnLoad ensures that this constructor is called when the Unity Editor is started.
  47. static ScenePlaybackDetector()
  48. {
  49. #if UNITY_2017_2_OR_NEWER
  50. EditorApplication.playModeStateChanged += e =>
  51. #else
  52. EditorApplication.playmodeStateChanged += () =>
  53. #endif
  54. {
  55. // Before scene start: isPlayingOrWillChangePlaymode = false; isPlaying = false
  56. // Pressed Playback button: isPlayingOrWillChangePlaymode = true; isPlaying = false
  57. // Playing: isPlayingOrWillChangePlaymode = false; isPlaying = true
  58. // Pressed stop button: isPlayingOrWillChangePlaymode = true; isPlaying = true
  59. if (EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying)
  60. {
  61. AboutToStartScene = true;
  62. }
  63. else
  64. {
  65. AboutToStartScene = false;
  66. }
  67. // Detect when playback is stopped.
  68. if (!EditorApplication.isPlaying)
  69. {
  70. IsPlaying = false;
  71. }
  72. };
  73. }
  74. }
  75. }
  76. #endif