How to execute a function X times per second.

I’m wanting to check the position of an object x times every second, and add those positions to an array. I believe the formula I have is correct, but I’m getting inconsistent and sometimes inaccurate results. I’m obviously missing something. Any help is appreciated.

var posArray = Array(Vector3);
var nextActionTime : float = 0.00;
var sampleRate : float = 20; //check twenty times per second

function Update () {
     if (Time.time > nextActionTime) {
          nextActionTime = Time.time + (1/sampleRate);
          GetPosition();
     }
}

function GetPosition () {
     posArray.Add(gameObject.transform.position);
}

This should be adding a value to the posArray 20 times per second (or, once every 0.05 seconds), but like I stated above it’s inconsistent. Would this “sample rate” be affected by frame rate? Is my math/logic flawed?

First, I doubt this code compiles since you use ‘time.time’ on line 7 with a lower case ‘t’. The likely issue is that at the time line 6 fires, you are past time. You could probably fix this by changing line 7 to:

nextActionTime = Time.time + (1.0/sampleRate) - (Time.time - nextActionTime);

Even with this change, there is some wiggle because Update() will not necessarily happen on the nextActionTime. And there may be issues when you game drags so that deltaTime grows to greater than your 1.0/sampleRate.

But a simpler solution would be to use InvokeRepeating(). In start just do:

InvokeRepeating("GetPosition", 0.0, 1.0/sampleRate);

Another solution would be to use some integer multiple of Time.deltaFixedTime and execute it in FixedUpdate(). By default FixedUpdate() is called 50 times per second so you could do it every other frame and get 25 samples per second.