Calculating interval dependants; ie: Velocity

I haven't been saving my scripts but just testing different approaches...

Having established a model of zero gravity flight using AddForce / AddRelative... and AddTorque / AddRelative..., I am trying to calculate velocity... Firstly taking "rigidbody.velocity.magnitude" to get m/s as velocity which reports back to a GUI label.

The problem arises when I want to take sample of say velocity or displacement, then wait one second (or greater, dependant on the granularity of response) and calculate say velocity by averaging the recorded variables?

My methods thus far have been to use the "yield.wait second(x)" but that has to be an "Ienumerator" or "Ienumarable" method else I get thrown a not correct method type class!

I have tried using "System.Timers" namespace and that doesn't seem to work in Unity?

So I am trying to sample say "rigidbody.velocity.magnitude" or -- ultimately-- say the x,y,z magnitudes of a Vector3 [ per second or other arbitary time interval ] to derive a GUI read out of acceleration ( displacement/time etc.)

I'm not asking for complete solution but assistance on the method by which I can say read ( current velocity, joystick input, Vector3 magnitudes, etc) on a periodic basis ( x seconds) and pass that to a GUI Label


Your first idea, using yield, was correct. What you need is a coroutine. You should look those up in the docs. THis should give you a basic idea (c#):

void Start() {

IEnumerator MyRoutine(float interval) {
  while (true) {
    yield return new WaitForSeconds(interval);

This will DoSomething() every 3 seconds.

Phew ... After a lot of head scratching I have it working so I have a template for interval dependant future functions, thanks to spree for the pointer.

using UnityEngine;

using System.Collections;

public class Speedometer_PhysX : MonoBehaviour {

// Use this for initialization
void Start () 
    StartCoroutine (Acceleration(cycletime));

public float cycletime = 1.0f;
public GameObject speedtarget;
float accResult;
float accSample1;
float accSample2;
decimal acceleration;
decimal speed;

// Update is called once per frame
void Update () 


IEnumerator Acceleration(float interval) 
        accSample1 = speedtarget.rigidbody.velocity.magnitude;
        yield return new WaitForSeconds(interval);
        accSample2 = speedtarget.rigidbody.velocity.magnitude;
        accResult = SampleAcceleration(accSample1,accSample2);

public float SampleAcceleration(float a1, float a2)
    return accResult = (a2-a1)/cycletime;

void OnGUI ()
    acceleration = (decimal) accResult; 
    speed = (decimal) speedtarget.rigidbody.velocity.magnitude;
    GUI.Label(new Rect(10,10,2000,25),"Speed = "+speed+ "  |  Acceleration = "+acceleration+" m/s");
    //GUI.Label(new Rect(20,20,2000,25),"new label");