Hey so i noticed some weird behavior on WaitForSeconds / WaitForSecondsRealtime.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class tesco : MonoBehaviour
{
public float value;
void Start()
{
StartCoroutine(Test());
}
IEnumerator Test()
{
while (value <= 1000000)
{
yield return new WaitForSecondsRealtime(0.01f);
value += 0.01f;
Debug.Log(value);
}
}
}
in this code Theoretically the value should be 1 in one second right?, but it’s not instead it took around 2-3s to make value become 1.
i don’t know why this happen but looks like it only happen on miniscule numbers of WaitForSeconds / WaitForSecondsRealtime.
so can anyone tell me what’s wrong with this please?
Unity (like most real-time game engines) uses a game loop where it renders one frame, then moves time forward a little bit, then renders another frame, etc.
Because of this, time moves forward in jumps. You want the picture you draw for a given frame to show everything at the same time, so you freeze the clock when you start making a frame, and then at the end of the frame time “catches up” to however much time has passed while you were making that frame. For instance, if you are running at 60 fps, then time instantly leaps forward by 1/60 of a second between frames.
When you say WaitForSeconds(x), what that really means is wait until the first frame that is at least x seconds into the future. So if you are running at 60 fps and you ask to wait for 5/60 seconds, you will wait for 5 frames. If you try to wait for 4.5/60 seconds, you will still wait for 5 frames–because the game clock jumps instantaneously from 4/60 to 5/60.
The smallest amount of time you can wait is 1 frame.
Also note that the exact amount of time between frames varies unpredictably–you can’t count on it being precisely 1/60 (or whatever) every time. In fact, if you don’t explicitly cap the frame rate, Unity will just render frames as fast as it can, and so the time before the next frame is “however long the last frame took to create”.
If precise timing is important, then you need to check the clock to see how long you actually waited, instead of assuming that it will be the exact amount of time you asked for.
thank you very much sir it really make things much more sensible, because of the naming “WaitForSeconds” i really got stuck at “it gonna wait for seconds i want” but now i know what should i do.