Difference Between WaitForSeconds(Time.deltaTime), yield return null, and WaitForEndOfFrame() in Unity

I have a question regarding the usage of different IEnumerator yield instructions in Unity. Specifically, I would like to understand the differences between:

  1. WaitForSeconds(Time.deltaTime)
  2. yield return null
  3. WaitForEndOfFrame()

Could someone please explain the differences in behavior and when each should be used? Thanks :slight_smile:

There are subtle differences in each one. The use case will mostly depend on your setup and what you are trying to achieve.

So, that said:

  1. WaitForSeconds(Time.deltaTime) →
    WaitForSeconds is dependent of TimeScale, so if your timeScale is let’s say 3, WaitForSeconds will wait for 1/3 of the time passed on the method (3x faster, it scales with timeScale).

And for the other 2, please check the following discussion, it will explain what you need to know^^ (a small google search got that result)

WaitForSeconds will yield for the specified number of seconds of game time (honoring time scaling - thanks, @OverGast). You can pass any number of seconds as a parameter. In your example, you are passing Time.deltaTime, which would mean to wait for the duration of the last frame. That’s not a common use of WaitForSeconds, but there’s nothing wrong with doing that, per se.

yield return null stops doing work until the next frame.

WaitForEndOfFrame stops doing work until all cameras have rendered, just before the frame is shown on the screen. This is often used as a way to do work that depends on the cameras having already done theirs, but before the frame is finished.

All of these are well documented.

Everything already said in this thread is 100%-spot-on. Let me also add:

Coroutines are NOT always an appropriate solution: know when to use them!

“Why not simply stop having so many coroutines ffs.” - orionsyndrome on Unity3D forums

Coroutines in a nutshell:

Splitting up larger tasks in coroutines:

Our very own Bunny83 has also provided a Coroutine Crash Course:

1 Like


;D

Well, I wouldn’t say that there’s nothing wrong with it since it wouldn’t make any sense. Waiting for deltaTime seconds means you wait either one frame or two or maybe even more frames and that would be kinda random depending on how the frame rate changes. If you’re currently on a low fps, say 30 fps you would wait for 1/30 seconds which is 0.033333 seconds. However if the next frame the fps jumps up to 120 fps, delta time would be 1/120 == 0.0083333 seconds. As a result the WaitForSeconds which was started at 1/30 would now last 4 frames. On the other hand if the numbers were reversed it would only wait one frame. There is never any reason to pass deltaTime to WaitForSeconds, ever.

1 Like