Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 356
user3071284 Avatar asked May 05 '26 22:05

user3071284


2 Answers

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.

like image 88
Felix K. Avatar answered May 08 '26 11:05

Felix K.


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());
}
like image 30
MahanGM Avatar answered May 08 '26 12:05

MahanGM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!