1
\$\begingroup\$

I want to run my code multiple times without using the Update() method, now, I could use a coroutine or an Invoke(), but since the Invoke() is not very performance friendly as a coroutine, my best option is to use a coroutine instead.

Now, my problem is, when my coroutine is completed and I want to restart it, how exactly should I do it?

Here is what I've done, but it doesn't work:

private void Start()
{
    StartCoroutine(DoSomething());
}

private IEnumerator DoSomething()
{
    //Does something
    yield return new WaitForSeconds(20f);
    //Does another thing
    yield return new WaitForSeconds(20f);
    StartCoroutine(DoSomething());
}
\$\endgroup\$
2

1 Answer 1

1
\$\begingroup\$

You can simply put an infinite loop in your coroutine.

private IEnumerator DoSomething()
{
    while(true) {
        //Does something
        yield return new WaitForSeconds(20f);
        //Does another thing
        yield return new WaitForSeconds(20f);
    }
}

You can still stop that loop by destroying the game object which started the coroutine or with StopCoroutine. If you have some exit condition for the loop which you want to check within the coroutine, you can either turn the infinite while-loop into a while-loop with a condition or break out of the loop with the break; keyword.

\$\endgroup\$
2
  • \$\begingroup\$ Thanks, I tried that before, and it didn't work, then I tried it again, right now and it works...so weird. Thanks again. \$\endgroup\$ Commented Mar 6, 2020 at 11:25
  • \$\begingroup\$ Note also that you can use “yield break;” to quit early. It’s the equivalent of “return;” within a coroutine. \$\endgroup\$
    – Ed Marty
    Commented Mar 6, 2020 at 14:51

You must log in to answer this question.

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