Skip to content

Commit

Permalink
Implement pause logic in CoroutineBase
Browse files Browse the repository at this point in the history
  • Loading branch information
Inspiaaa committed Sep 5, 2024
1 parent d50ddd1 commit 2771f22
Showing 1 changed file with 48 additions and 9 deletions.
57 changes: 48 additions & 9 deletions src/CoroutineBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -56,15 +57,7 @@ public void Init()

if (IsAlive)
{
if (!Manager.IsPaused)
{
hasCalledStart = true;
OnStart();
}
else
{
hasCalledStart = false;
}
UpdateRunState(Manager.IsPaused);
}
}

Expand Down Expand Up @@ -239,7 +232,19 @@ private void RemoveChild(CoroutineBase coroutine)
}
}

/// <summary>
/// Called when the game is paused or unpaused.
/// </summary>
public void OnGamePausedChanged(bool isGamePaused)
{
UpdateRunState(isGamePaused);
UpdateChildrenAboutPausedChanged(isGamePaused);
}

/// <summary>
/// Informs the child coroutines that the game has been paused / unpaused.
/// </summary>
private void UpdateChildrenAboutPausedChanged(bool isGamePaused)
{
CoroutineBase child = firstChild;
while (child != null)
Expand All @@ -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();
}
}
}

0 comments on commit 2771f22

Please sign in to comment.