Unity3D - Using Time.deltaTime as wait time for a coroutine
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");
}