What is "Time.deltaTime" in Unity?

In game development, timing and synchronization play an essential role in creating immersive user experiences. Unity provides a variable named Time.deltaTime which helps to achieve smooth animations, consistent frame rates, and realistic interactions with the games.

Understanding Time.deltaTime

Definition

Time.deltaTime is a Unity specific variable that represents the time interval in seconds it took from the last frame to the current frame. It measures the interval between the current frame and the last one.

Purpose

In an interactive video game, rendering frame rates can fluctuate due to the hardware differences, system load, or other factors. Such variations can lead to animations appearing too fast on powerful machines and too slow on slower ones. By using Time.deltaTime, you can ensure that the animations and movements of the GameObjects are consistent across different platforms and hardware.

Formula

  • The formula is used to normalize calculations according to the rate at which the machine renders each frame.

  • If we multiply the above equation with the specific vector of the GameObject inside our C# script, we get a fixed speed no matter what the time frame is.

Example

Let's say we have a computer AA that can only run a game with 2020 frames per second (FPS) and a computer BB that can run a game with 100100 FPS. If we do not use Time.deltaTime inside the update method in the C# script, the computer AA (low FPS) will run the game at a slower rate as compared to the computer BB (high FPS).

When you use Time.deltaTime in C# scripts, you work with the time it takes for each frame to complete, regardless of the actual frame rate. It ensures that the game elements move and behave smoothly regardless of the variations in the frame rate.

transform.Translate(new Vector3(0f, 5f, 0f) * Time.deltaTime);
// Computer A: 20 fps
// Time.deltaTime = 1 / 20 = 0.05
transform.Translate(20 * new Vector3(0f, 5f, 0f) * 0.05);
// It means that we move 5 units per second.
// Computer B: 100 fps
// Time.deltaTime = 1 / 100 = 0.01
transform.Translate(20 * new Vector3(0f, 5f, 0f) * 0.01);
// It means that we move 5 units per second.

Explanation

  • Line 1: Time.deltaTime ensures that the same script works consistently across different frame rates. The Translate method is used to transform the position of the GameObject along the y-axis.

  • Lines 3–6: These lines calculate the Time.deltaTime at 20 FPS. It then multiplies the time frame with the FPS to get the constant speed.

  • Lines 8–11: These lines calculate the Time.deltaTime at 100 FPS. It then multiplies the time frame with the FPS to get the constant speed.

Benefits of using Time.deltaTime

Given below are the advantages of using Time.deltaTime in Unity.

  • Consistency: By using Time.deltaTime, you can achieve a consistent user experience across various platforms, devices, and frame rates.

  • Realism: Realistic animations and physics interactions are essential for immersive game experiences. Time.deltaTime helps in maintaining these elements regardless of varying computational resources.

  • Optimization: Time.deltaTime ensures that the game runs smoothly on every machine and on every set up, enhancing the accessibility.

Note:

  • In Unity, you do not explicitly set the frames per second (FPS) as a fixed value.

  • Instead, Unity's game loop runs as fast as the hardware allows and tries to maintain a consistent frame rate.

  • The frame rate is influenced by the complexity of the scene, the performance of the computer or device, and the efficiency of your scripts and game mechanics or physics.

Sample project

The sample project shows a rotating cube which changes it color over time.

Note:

  • Press P to rotate the cube.

  • Press S to stop rotating the cube.

  • A sample C# script to rotate the GameObject and the use of Time.deltaTime is given below.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RotatingObject : MonoBehaviour
{
public float degreesPerSecond = 60.0f;
public bool isRotating = false;
void Update()
{
// Check for user input to start or stop rotation
if (Input.GetKeyDown(KeyCode.P))
{
isRotating = !isRotating;
}
// Rotate the object if the rotation is active
if (isRotating)
{
transform.Rotate(0, 0, degreesPerSecond * Time.deltaTime);
}
}
}

Explanation

  • Lines 1–3: These lines make all the necessary imports.

  • Line 5: A class is declared named RotatingObject. It inherits methods from the class MonoBehaviour, a base class in Unity for scripts attached to the specific GameObjects.

  • Line 7: It declares a float variable named degreesPerSecond, which represents the rotation speed of the object in degrees per second.

  • Line 8: This line declares a bool variable named isRotating. It is set to false initially. It controls whether the object is currently rotating.

  • Lines 10–22: The Update() function is called once per frame. It checks if the P key (KeyCode.P) is pressed by Input.GetKeyDown() method.

    • If the P key is pressed, it toggles the value of the isRotating variable.

      • If the GameObject is rotating, it will stop rotating.

      • If the GameObject is not rotating, it will start rotating.

    • After checking the user input, it checks whether the value isRotating is true.

      • If isRotating is true, it rotates the object around its z-axis by a value determined by the degreesPerSecond * Time.deltaTime.

      • Time.deltaTime is used to make the rotation frame rate-independent to ensure the smooth rotation of the GameObject regardless of the frame rate.

import React from 'react';
require('./style.css');

import ReactDOM from 'react-dom';
import App from './app.js';

ReactDOM.render(
  <App />, 
  document.getElementById('root')
);

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved