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