I have a diffusion simulation that runs locally in Unity. I use a coroutine to simulate a simulation step, so that I can run it less often than Update to help performance if I need to:
private IEnumerator CalculateSimulationStep()
{
while(true)
{
...simulate diffusion...
yield return new WaitForSeconds(1 / stepsPerSec)
}
}
But I want to calculate as many steps as reasonable performance will allow, since more data is better. So I tried making stepsPerSec responsive to a separate FPS counter’s readings:
private void AdaptStepsPerSec()
{
if (curFPS.AverageFPS < 30)
{ // If we're running too slowly, do fewer simulation steps per second
stepsPerSec--;
}
else
{ // If we're above our ideal FPS, we can afford to do more simulation steps
stepsPerSec++;
}
if(stepsPerSec < 5)
{ // Limit our steps per second to 5
stepsPerSec = 5;
}
}
After writing this code, my stepsPerSec started skyrocketing up into the 1000’s without any performance drop, and with my simulation loop still seeming to only be running 30ish times per second.
It makes me think that coroutines can’t update more often than the Update function. I believe this is because the game logic loop will only check if a coroutine is due to run once per frame.
It would be fine to only run this once per frame; You literally could not see changes in the data more often than once per frame, and if I run WaitForSeconds(0) then I essentially have an Update function. But is it possible to run a coroutine more often than once per frame?