Can CustomYieldInstruction return a value after it has completed?

I’m trying to write a CustomYieldInstruction that can tell how many frames has elapsed while waiting, using a target framerate as a reference. The purpose is that since Coroutines seem to be framerate dependent, so if the wait time is shorter than the time between frames (when framerate has dropped), the time waited is actually longer, which is very noticeable if you do repeated waits in a while loop. The point here is that if I can get the amount of frames that should have passed if the game was running at the target framerate or faster, I can adjust the processing in a single iteration to compensate.

Here is some code I’ve already written:

using UnityEngine;

public class WaitForSecondsElapsedFrames : CustomYieldInstruction
{
    private const float targetFramerate = 60f;
    private float timer = 0f;
    private float accumulatedDeltaTime = 0f;
    private float framesElapsed = 0f;

    public override bool keepWaiting
    {
        get
        {
            timer -= Time.deltaTime;
            accumulatedDeltaTime += Time.deltaTime;
            
            if (timer <= 0f)
            {
                return false;
            }
            else
            {
                // Output this value to user somehow ???
                framesElapsed = accumulatedDeltaTime * targetFramerate;
                return true;
            }
        }
    }
    
    public WaitForSecondsElapsedFrames(float time)
    {
        timer = time;
    }
}

Use Time.frameCount to count frames. Adding delta times gives you an accumulated value of past delta times but you cannot derive the number of frames from it!

1 Like

It’s just code… you can make a getter to get whatever value(s) you want out of it, either before, during or after its use.

ALSO… this statement:

makes me think you probably need to be aware of this information:

Here is some timing diagram help:

1 Like