# How can I make a coroutine run for a specific number of times in Unity?

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!

• 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. Jul 13 '18 at 11:44

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;
}
}