TL,DR: is it safe to use Time.deltaTime as the wait time for the yield in a coroutine?
Often to avoid unnecessary logic inside Update() for short lived functionality I'll run a coroutine instead. For example in my game I have a slow coroutine that periodically checks the distance between NPCs and the player, if that distance is under some threshold I'll then run a more frequent coroutine with more expensive line of sight testing using raycasting etc. This seems much more efficient than checking everything constantly in Update().
My question is this: is it safe to use Time.deltaTime as the wait time for the yield, thereby simulating Update() for the duration of the coroutine? i.e. yield return new WaitForSeconds(Time.deltaTime);
Since deltaTime is not constant what happens if the next frame takes longer than the last - is the coroutine delayed until the next frame, or is something horrible happening like the whole frame being delayed until the coroutine finishes? I'm tempted to allow a buffer for safety e.g. yield return new WaitForSeconds(Time.deltaTime * 1.2f);
but ideally I'd like it to execute precisely every frame.
is it safe to use Time.deltaTime as the wait time for the yield in a coroutine?
No. That's not how to use the WaitForSeconds
function. WaitForSeconds
takes in seconds as a parameter not the tiny values provided by Time.deltaTime
in every frame.
Below is an example of how to use the WaitForSeconds
function.
IEnumerator waitFunction1()
{
Debug.Log("Hello Before Waiting");
yield return new WaitForSeconds(3); //Will wait for 3 seconds then run the code below
Debug.Log("Hello After waiting for 3 seconds");
}
As for waiting with Time.deltaTime
, you usually use it in a while
loop in addition to another float
variable you will increment
or decrement
until you reach the wanted value.The advantage of using Time.deltaTime
is that you can see how much waiting time is left while waiting. You can use that for a countdown or up timer. You also put yield return null;
in the while
loop so that Unity will allow other scripts to run too and your App won't freeze. Below is an example of how to use Time.deltaTime
to wait for 3 seconds. You can easily turn it into a countdown timer.
IEnumerator waitFunction2()
{
const float waitTime = 3f;
float counter = 0f;
Debug.Log("Hello Before Waiting");
while (counter < waitTime)
{
Debug.Log("Current WaitTime: " + counter);
counter += Time.deltaTime;
yield return null; //Don't freeze Unity
}
Debug.Log("Hello After waiting for 3 seconds");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With