C #: how the trigger stops the cycle

I want to understand the concept coroutine, I don’t know why the code stops when it is print 1,2,3. But in this code loop, it should execute 30 times and print values ​​from 1 to 30.

public class NewCore : MonoBehaviour
{
    void Start ()
    {
        StartCoroutine (MyCoroutine (0.52f));
        StartCoroutine (CoroutineKiller (2f));
    }

    IEnumerator MyCoroutine (float delay)
    {
        int value = 0;
        while (value < 30)
        {
            yield return new WaitForSeconds (delay);//wait
            value ++;
            print (value);
        }

        StartCoroutine (MyCoroutine (delay));
    }

    IEnumerator CoroutineKiller (float delay)
    {
        yield return new WaitForSeconds (delay);
        StopAllCoroutines ();
    }
}
+4
source share
2 answers

You print values ​​from 1 to 30 with a delay of 0.52 seconds, but after 2 seconds you stop doing this (you call StopAllCoroutines). That is why you see only 1, 2 and 3.

Try commenting StartCoroutine (CoroutineKiller (2f));or give it more time to see how it controls the flow stop.


Coroutines is similar to threads, although not very, but in the sense that a call StartCoroutinedoes not block the code.

So when you do this:

void Start ()
{
    StartCoroutine (MyCoroutine (0.52f));
    StartCoroutine (CoroutineKiller (2f));
}

, , .

, :

void Start()
{
    StartCoroutine(F());
}

IEnumerator F()
{
    // by yielding the Coroutine, it will block the execution of
    // this coroutine (F) until MyCoroutine finishes
    yield return StartCoroutine(MyCoroutine(1.52f));

    // This is no longer doing much, really.
    yield return StartCoroutine(Killer(2f));

    print("done");
}

Execution Order , , .

+3

, StopCoroutine (MyCoroutine()); CoroutineKiller 2 . ( 2f. , WaitForSeconds). , MyCoroutine 3 (0,52 + 0,52 + 0,52 = 1,56) , 1,2,3 .

0
source

Source: https://habr.com/ru/post/1613001/


All Articles