Coroutine lasts longer than expected

Hello everyone, here I have something that peeked my interest when working with the Coroutines.
So I’m drawing a line using the “LineRenderer”, The points of the line are inside a list and the number of points can vary. Nevertheless I want the process to last on second in total to be drawn.
With this in mind I though about working with a Coroutine and using WaitForSecondsRealtime(). My logic is that each point will be drawn in between segments of time equals to “1/NumberOfPoints”, So I wrote the next piece of code:

IEnumerator drawingAnimation()
    {
        float timePerSegment = 1f/availablePath.Count;
        int lineIndex = 0;
        for(int i = availablePath.Count-1; i >=0 ;i--)
        {
            pencil.positionCount++;
            pencil.SetPosition(lineIndex, mazeCells[availablePath[i]].transform.position + Vector3.up * (wallHeight +2));
            lineIndex++;
            yield return new WaitForSecondsRealtime(timePerSegment);
        }
        drawingRoutin = null;
        Debug.Log("Finished Drawing Line");
    }

The process runs fine, but it takes longer than one second to be completed.In fact I decided to have another Coroutine taking the time for this process to be completed, Here is a screen capture:

Here is some more data regarding this results:
The total number of points in the list is 170.
timePerSegment = 0.005882353

Now my questions are:
Why do you think the process takes more than what I expect it to take?
Am I not taking something into consideration? (regarding the WaitForSecondsRealTime())

You will never get 170 updates completed in one second. It will never exceed the rate at which Update() is being called.

See the Unity lifecycle graph for a feeling on when coroutines are updated relative to Update. Specifically only “one step” of the coroutine is called.

It is up to you to do the bookkeeping to “make this so,” but it’s not too hard. You can just do a “yield return null;” (which says “always run me the next frame”) and then query Time.deltaTime to see how much time actually passed, then do the required number of your 1 / 170th second steps to meet up.

1 Like

Interesting, I’ll have a complete read on the execution order and I will give a go on the book keeping. As you said it really does not seem like something out of the world.