Menu
CoddyTech

Unscaled Time

Part of the Building Real Games section of Coddy's Unity journey. Lesson 36 of 60.

A paused or slowed game still needs a real clock for some things: a pause menu that animates, a countdown before play goes on, a freeze that must end by itself. Time.unscaledDeltaTime is the real time since the last frame, whatever Time.timeScale is, and Time.unscaledTime is the real time since the game started. This pause menu turns its loading wheel with real time, so the wheel spins while the game is paused:

void Update()
{
    wheel.Rotate(0f, 0f, -180f * Time.unscaledDeltaTime);   // half a turn a second, paused or not
}

Coroutines have the same pair. WaitForSeconds counts game time, so at Time.timeScale = 0 it never ends; WaitForSecondsRealtime counts real seconds. Started when the menu opens, this coroutine blinks the menu's title every half second:

IEnumerator Blink()
{
    while (true)
    {
        title.SetActive(!title.activeSelf);
        yield return new WaitForSecondsRealtime(0.5f);
    }
}

Use the scaled values for gameplay, which should stop when the game stops, and the unscaled ones for what must run while it is paused or slowed: menus, their animations, and timers that end a pause. Invoke has no real time version: it always counts game time.

challenge icon

Challenge

Medium

Give the anvil a hit stop: the whole game freezes for a moment when it lands.

  1. In Anvil.cs, write IEnumerator HitStop(): Time.timeScale = 0f;, then yield return new WaitForSecondsRealtime(freezeTime);, then set it back to 1f.
  2. Write void OnCollisionEnter(Collision collision) that calls StartCoroutine(HitStop());.

Press Play and drop anvils with Space: each landing freezes the game for 0.3 seconds. Then Check.

Try it yourself

using System.Collections;
using UnityEngine;

public class Anvil : MonoBehaviour
{
    public float freezeTime = 0.3f;

    // Freeze the game for freezeTime real seconds when the anvil hits something
}

All lessons in Building Real Games

Practice on your own: Unity playground