2
\$\begingroup\$

I have several coroutines always running.

I want to put these coroutines on hold as I set the game to pause mode.

Consider the content of these coroutines as follows

while (timeleft > 0)
        {
            if (pause)
            {
                continue;
            }
            ...
            timeleft -= Time.FixedDeltaTime;
            yield return null;
        }

I thought that would be okay to insert the if(pause) clause to have the coroutines to wait while pause is up.

What, insted happens is that (I guess) these infinite loops make unity not responding so that I have to kill the process.

Can I be right in thinking that the system does not like coroutines to be in a potential infinite loop? Or that is just okay and I have to heavily debug somewhere else?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

It has nothing to do with it being a coroutine. It's an infinite loop, that can't exit. You need to return control to the code that's calling the coroutine. Your idea is good, it's just missing that component. If you're paused, just return without doing anything:

while (timeleft > 0)
{
    if (pause)
    {
        yield return null;
        continue;
    }
    ...
    timeleft -= Time.FixedDeltaTime;
    yield return null;
}

This will cause a return to the calling code, without decreasing the time remaining. Later, when the coroutine gets control back, it'll continue (like you wanted), starting back at the top of the loop. If you're no longer paused at that time, it'll proceed as normal.

\$\endgroup\$
3
  • \$\begingroup\$ That was was like a purge! Great, you opened my mind. I think I need to focus a little bit more on coroutines theory. \$\endgroup\$
    – Leggy7
    Mar 15, 2016 at 23:35
  • 1
    \$\begingroup\$ Think of them like state machines. I'm pretty sure there's an article out there that describes them as such. \$\endgroup\$
    – House
    Mar 16, 2016 at 0:26
  • \$\begingroup\$ Coroutines and State Machines: labs.pedrofelix.org/guides/kotlin/coroutines/… \$\endgroup\$
    – Michael K.
    Aug 5, 2019 at 6:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .