Execute code every x seconds with Update()

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
    }
}

See InvokeRepeating. It's designed to do exactly this.

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
    }
}

How about running a coroutine function?

IEnumerator DoCheck() {
    for(;;) {
        // execute block of code here
        yield return new WaitForSeconds(.1f);
    }
}

and run this in your start or something

StartCoroutine("DoCheck");

This will let the function to run every tenth second. You can change the argument to change time.
Hope that helps.

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
    }
}

This works for me,

public float period = 0.0f;
void Update()
{
    if (period > [Time Interval])
    {
        //Do Stuff
        period = 0;
    }
    period += UnityEngine.Time.deltaTime;
}