Overview: Keeping Track of Time Manual     Reference     Scripting  
Scripting
Overview: Keeping Track of Time

The Time class contains a very important class variable called deltaTime. This variable contains the amount of time since the last call to Update or FixedUpdate (depending on whether you are inside an Update or a FixedUpdate function).

So the previous example, modified to make the object rotate with a constant speed not dependent on the frame rate becomes:

JavaScript
function Update() {
transform.Rotate(0, 5 * Time.deltaTime, 0);
}

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
void Update() {
transform.Rotate(0, 5 * Time.deltaTime, 0);
}
}

import UnityEngine
import System.Collections

class example(MonoBehaviour):

def Update():
transform.Rotate(0, (5 * Time.deltaTime), 0)

Moving the object:

JavaScript
function Update() {
transform.Translate(0, 0, 2 * Time.deltaTime);
}

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
void Update() {
transform.Translate(0, 0, 2 * Time.deltaTime);
}
}

import UnityEngine
import System.Collections

class example(MonoBehaviour):

def Update():
transform.Translate(0, 0, (2 * Time.deltaTime))

If you add or subtract to a value every frame chances are you should multiply with Time.deltaTime. When you multiply with Time.deltaTime you essentially express: I want to move this object 10 meters per second instead of 10 meters per frame. This is not only good because your game will run the same independent of the frame rate but also because the units used for the motion are easy to understand. (10 meters per second)

Another example, if you want to increase the range of a light over time. The following expresses, change the radius by 2 units per second.

JavaScript
function Update() {
light.range += 2.0 * Time.deltaTime;
}

using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
void Update() {
light.range += 2.0F * Time.deltaTime;
}
}

import UnityEngine
import System.Collections

class example(MonoBehaviour):

def Update():
light.range += (2.0F * Time.deltaTime)

When dealing with rigidbodies through forces, you generally don't multiply by Time.deltaTime since the engine already takes care of that for you.