# calculate a falling number

How should I go about calculating the speed of number that drops at a variable rate. I think the rate should be calculated in lateupdate, while the number would be changing during update.

It would probably be the difference between a previous number and the current number, but the part I don’t know how to do is calculate the previous number. If you have any ideas let me know

I often do these things in a CoRoutine - rather than between Update and LateUpdate etc.
This also means you can calculate rates very efficiently with low overhead - because you don’t always need to calculate this every frame.

Here’s how I’d do it:

``````public class CalcRate : MonoBehaviour {

public float Rate; // This is the answer you want - the rate of change over time
public float Frequency = 0.1f;  // How often you want this to be calculated - smaller = more accurate
public float ValueToTrack;  // The value that is changing - your code would just update this at any time

private float _sampleTime;
private float _previousValue;

void Start () {
// Start up the coroutine
StartCoroutine(CalculateRate());
}

IEnumerator CalculateRate() {
for(;;) {
// Record the current Value
_previousValue = ValueToTrack;
_sampleTime = Time.time;

// Wait a little bit
yield return new WaitForSeconds(Frequency);

// Calculate the rate - difference divided by amount of time passed
float diff = ValueToTrack - _previousValue;
Rate = diff / (Time.time - _sampleTime);
}
}

// Update is called once per frame
void Update () {
// Don't need this
}

void OnDestroy() {
StopAllCoroutines();
}
}
``````

Some might argue this is overkill … But I think the benefit of being able to change the frequency to something dialled down (low rate) or something dialled up (high rate) gives you the accuracy you need, and saving lots of CPU.