简体   繁体   中英

Why does this Coroutine only run once?

"Something" is only printed once...

IEnumerator printSomething;

void Start () {

    printSomething = PrintSomething();
    StartCoroutine (printSomething);

}

IEnumerator PrintSomething () {

    print ("Something");

    yield return null;
    StartCoroutine (printSomething);

}

The misstake in your approach is that you save the enumerator. A enumerator is already "enumerating" therefore giving the enumerator to the StartCoroutine -method twice basically results in direct exit of the coroutine as the enumerator has been used before. Starting the coroutine again can be done by calling the function again.

StartCoroutine(PrintSomething());

But instead of starting the coroutine over and over again try to use a loop inside instead.

while (true)
{
    print("something");
    yield return null;
}

This is better as internal handling of the coroutine and its overhead is unknown.

Try co-routine's name instead of a pointer. Or co-routine itself.

IEnumerator PrintSomething () 
{
    print ("Something");

    yield return null;

    StartCoroutine ("PrintSomething");
}

Or

IEnumerator PrintSomething () 
{
    print ("Something");

    yield return null;

    StartCoroutine (this.PrintSomething());
}

I ran into this exact same issue, Felix K. is right in that it assumes the IEnumerator has already been run and just immediately returns. My solution was to pass the function itself so that we generate a new IEnumerator each time it's called. I hope this helps someone else!

public IEnumerator LoopAction(Func<IEnumerator> stateAction)
{
    while(true)
    {
        yield return stateAction.Invoke();
    }
}

public Coroutine PlayAction(Func<IEnumerator> stateAction, bool loop = false)
{
    Coroutine action;
    if(loop)
    {
        //If want to loop, pass function call
        action = StartCoroutine(LoopAction(stateAction));
    }
    else
    {
        //if want to call normally, get IEnumerator from function
        action = StartCoroutine(stateAction.Invoke());
    }

    return action;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM