IEnumerator – call a method with delay in Unity

    // Function WaitAndPrint() will be called with 2s delay
    IEnumerator coroutine;

    void Start()
    {
        coroutine = WaitAndPrint(2.0f);
        StartCoroutine(coroutine);
    }

    IEnumerator WaitAndPrint(float waitTime)
    {
        yield return new WaitForSeconds(waitTime);
        print(Time.time);
    }

In order to call a method all the time we can use a while loop. In the example below we will print a number of seconds that passed since the execution of the program.

    IEnumerator coroutine;

    void Start()
    {
        coroutine = WaitAndPrint(1.0f);
        StartCoroutine(coroutine);
    }

    IEnumerator WaitAndPrint(float waitTime)
    {
        while (true)
        {
            yield return new WaitForSeconds(waitTime);
            print(Time.time.ToString("00"));
        }
    }

Now, let’s create a program that will count seconds up to 10.

    void Start()
    {
        StartCoroutine("WaitAndPrint", 1.0f);
    }

    IEnumerator WaitAndPrint(float waitTime)
    {
        int nrOfSeconds = 0;
        while (nrOfSeconds < 10)
        {
            yield return new WaitForSeconds(waitTime);
            nrOfSeconds++;
            print(nrOfSeconds.ToString());
        }
    }

Let me show you one more example that might come handy. In many cases we would like to stop the coroutine that runs in the loop. We can do it by StopCoroutine() method. In the example below we will stop the counting with pressing the spacebar.

    void Start()
    {
        StartCoroutine("WaitAndPrint", 1.0f);
    }

    IEnumerator WaitAndPrint(float waitTime)
    {
        int nrOfSeconds = 0;
        while (nrOfSeconds < 10)
        {
            yield return new WaitForSeconds(waitTime);
            nrOfSeconds++;
            print(nrOfSeconds.ToString());
        }
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            StopCoroutine("WaitAndPrint");
        }
    }

Dodaj komentarz

Twój adres email nie zostanie opublikowany.