Execute IEnumerator In 1 Frame

Excute below codes will result it to be finished after 200 frames. How to make it to finish in 1 frame?

StartCoroutine(JustTest());

IEnumerator JustTest(){
    for(int i=0;i<200;i++){
        yield return StartCoroutine(TT());
    }
}

IEnumerator TT(){
    yield break;
}

Edit 1: Perhaps the question could be “How to call IEnumerator so it is like calling a normal function?”

How about something like this:

IEnumerator e = JustTest();
while(e.MoveNext())
{
// Whatever...
}

e.MoveNext() essentially executes the next iteration of your code.

An IEnumerator is just an interface which enables the user to iterate over the object that implements the interface and returns an object for each iteration. Unity uses this interface to implement coroutines. When you use the usual Unity-coroutine-return values you should only use it with StartCoroutine or the actual function is not guaranteed.

If you have a custom IEnumerator, you can iterate over it like PaulR said or use a foreach loop:

foreach(var result in JustTest())
{
    // do nothing
}

This will effectively start all 200 sub coroutines (TT) at once.

Actually there’s not much magic behind a generator function (function that uses yield).

Just an example:

IEnumerator Test()
{
    yield return "Hello";
    yield return "World";
    yield return "!!!";
}

foreach(string S in Test())
{
    Debug.Log(S);
}

This will print 3 lines

Hello
World
!!!

Whenever you use StartCoroutine, Unity will iterate through your “collection” and interpret the returned values how long it should suspend before it continues.

So you can’t influence the behaviour of StartCoroutine.

Well. In your case, just don’t use coroutines at all.

JustTest();

void JustTest{
   for(int i=0;i<200;i++){
        TT();
    }
}

If you don’t yield return the coroutine, it won’t wait. So just remove the yield return, and add a yield break so it will compile.

    IEnumerator JustTest()
    {
        for (int i = 0; i < 200; i++)
        {
            //yield return StartCoroutine(TT());
            StartCoroutine(TT());
        }

        yield break;
    }