0
\$\begingroup\$

I use coroutines in unity, with while(true) condition, which runs it indefinitely. I need to make the coroutine run for a specific number of times, let's say 10 times. Any pointers will be much appreciated!

\$\endgroup\$
  • \$\begingroup\$ I'd recommend working your way through a few more beginner programming tutorials, as loop control flow is usually one of the first few things they cover. More complicated game behaviours will get much easier to tackle once you have these fundamentals to build on, and you'll also gain the vocabulary to ask more complex questions when you need help. \$\endgroup\$ – DMGregory Jul 13 '18 at 11:44
2
\$\begingroup\$

Unity Coroutines will exit automatically when they reach the end of the function. Thus, the answer is simply to use a for loop instead of a while loop.

If you need the number of times it runs for to vary, you can pass this in as a function (see this).

For Example:

IEnumerator DoSomething(int loops)
{
    for (int idx = 0; idx < loops; idx++)
    {
        print("DoSomething Loop");

        // Yield execution of this coroutine and return to the main loop until next frame
        yield return null;
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.