diff --git a/src/CoroutineBase.cs b/src/CoroutineBase.cs index 0bd3792..2d9c638 100644 --- a/src/CoroutineBase.cs +++ b/src/CoroutineBase.cs @@ -19,6 +19,7 @@ public class CoroutineBase protected CoroutineBase previousSibling, nextSibling; public bool IsAlive { get; private set; } = true; + public bool IsRunning { get; private set; } = false; public bool ShouldReceiveUpdates { get; private set; } = false; private bool hasCalledStart = false; @@ -56,15 +57,7 @@ public void Init() if (IsAlive) { - if (!Manager.IsPaused) - { - hasCalledStart = true; - OnStart(); - } - else - { - hasCalledStart = false; - } + UpdateRunState(Manager.IsPaused); } } @@ -239,7 +232,19 @@ private void RemoveChild(CoroutineBase coroutine) } } + /// + /// Called when the game is paused or unpaused. + /// public void OnGamePausedChanged(bool isGamePaused) + { + UpdateRunState(isGamePaused); + UpdateChildrenAboutPausedChanged(isGamePaused); + } + + /// + /// Informs the child coroutines that the game has been paused / unpaused. + /// + private void UpdateChildrenAboutPausedChanged(bool isGamePaused) { CoroutineBase child = firstChild; while (child != null) @@ -249,4 +254,38 @@ public void OnGamePausedChanged(bool isGamePaused) child = child.nextSibling; } } + + + private void UpdateRunState(bool isGamePaused) + { + bool shouldBeRunning = RunMode switch { + CoRunMode.Always => true, + CoRunMode.Pausable => !isGamePaused, + CoRunMode.WhenPaused => isGamePaused + }; + + if (IsRunning == shouldBeRunning) + { + return; + } + + IsRunning = shouldBeRunning; + + if (shouldBeRunning) + { + if (hasCalledStart) + { + OnResume(); + } + else + { + hasCalledStart = true; + OnStart(); + } + } + else + { + OnPause(); + } + } } \ No newline at end of file