I am starting a coroutine which iterates a loop number of times and waiting a certain time between each iteration. But complation of the loop takes way more longer than the expected. Here is the code:
private IEnumerator CO_AddBladesInTime(int count, Blade blade)
{
var _spawnPos = blade.transform.position;
var _counter = 0;
var _firstTime = Time.time;
var _calculatedTime = 0f;
Debug.Log("entered coroutine at " + _firstTime);
while (_counter < count)
{
_counter++;
// AddNewBlade(_spawnPos, blade.Level);
var _waitTime = bladeSpawnFreq / count;
_calculatedTime += _waitTime;
yield return new WaitForSeconds(_waitTime);
}
var _secondTime = Time.time;
Debug.Log("exited coroutine at " + _secondTime);
Debug.Log($"waited {_secondTime - _firstTime}");
Debug.Log($"expected wait time {_calculatedTime}");
}
Here is the results:
Am I missing something?

As was mentioned before currently your Coroutine will wait for a minimum of
countframes.WaitForSecondsbasically kind of works similar toso even if the
timeToWaitis very very small like e.g.0.00001it will still wait for an entire frame - which assuming a frame-rate of60 f/shas a length of0.017seconds!Also not sure why you did use this
I would assume
bladeSpawnFreqalready refers to how many objects to spawn per second. Instead I would rather expect you to calculatethe time in seconds between two spawns.
So this might be going too fancy now and there might be more straight forward solutions but what you could do is going asynchronous.
So what happens here is
ScheduleSpawnstask as an asynchronous task (-> might even be running on a different thread).Task.Delayis happening on a milliseconds basis and way more precise than the Unity frames (as said for 60 fps one frame alone is already 17 ms long)Note that still of course this might be very slightly to long in the end due to the often mentioned nature of frames being quite long ;)