Pausing Co-routine using a boolean causes Unity to hang

I have a co-routine:

 private IEnumerator GameClock()
    {
        while (isRunning)
        {
            Debug.Log("Check if paused");
            if (!isPaused)
            {
                currentDate++;
                yield return new WaitForSeconds(timescalefactor);
            }
            else {
                Debug.Log("Is Paused");
            }
        }
    }

Like this, it runs perfectly fine. Now however, I’m trying to have a pause button so that the player can pause the game to think etc. I’ve linked a button to a function that flips the isPaused boolean to false, but when that button is clicked, the boolean flips and then Unity hangs/does not respond.

I’ve checked and the boolean-flipping function is working/isn’t causing the system to hang, ie. I can get print statements in that function to print. However, the code doesn’t seem to get to the first ‘Check if Paused’ debug statement (or at least, it doesn’t get printed out before the system hangs) in the enumerator.

Any idea what has happened or how to fix it?

You do not have any yield if it is paused. simply add something like yield return null; to the else statement.

The reason why it isn’t working is because you don’t have any yield statements if isPaused is true, so the while loop goes on forever and Unity crashes.

I’m not 100% sure why this is, but I think it’s because unity needs to wait for a co-routine (and code in general) and a while loop says do x code a until a statement is false. If this statement never becomes false or you don’t have a yield statement to tell Unity to move on, Unity is always waiting and this seems to crash the program.

You can add a yield return null; in the else statement and then it will only run every frame.

An alternate solution is to use Time.timeScale = 0;
I believe that this will tell Unity to stop physics and time-based co-routines, but I could be wrong. In any case, I find that it looks a bit nicer.