I want to call a block of code every 0.1 seconds using Update() (assuming that this is the best way to do it), but it tends to run on average every .11 - .12 seconds instead.
private float time = 0.0f;
public float interpolationPeriod = 0.1f;
void Update () {
time += Time.deltaTime;
if (time >= interpolationPeriod) {
time = 0.0f;
// execute block of code here
}
}
Alternatively, if you particularly want to do it in Update, you could change your code to mark the next event time rather than accumulating the delta time, which will be more accurate:
private float nextActionTime = 0.0f;
public float period = 0.1f;
void Update () {
if (Time.time > nextActionTime ) {
nextActionTime += period;
// execute block of code here
}
}
If you like doing it in update, I would just do a 1 line change to below.
This way if you hit update when time is at 0.11f, you subtract 0.1f and are already at 0.01f before getting to your next update. You’ll average out a lot closer to 0.1f in the long run than your original implementation.
private float time = 0.0f;
public float interpolationPeriod = 0.1f;
void Update () {
time += Time.deltaTime;
if (time >= interpolationPeriod) {
time = time - interpolationPeriod;
// execute block of code here
}
}