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
MediumGive the anvil a hit stop: the whole game freezes for a moment when it lands.
- In
Anvil.cs, writeIEnumerator HitStop():Time.timeScale = 0f;, thenyield return new WaitForSecondsRealtime(freezeTime);, then set it back to1f. - Write
void OnCollisionEnter(Collision collision)that callsStartCoroutine(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
2Buttons and Screens
Buttons and onClickLambdasWiring in the InspectorPanels On and OffHealth BarsRecap: Upgrade Shop5Saving with PlayerPrefs
Save a NumberLoad with a DefaultHigh ScoreSave SettingsRecap: Coins in the Bank3The Game Manager
One Script Runs the GameThe SingletonGame StatesSwitching on the StateRecap: Round Manager6Project: Endless Runner
Three LanesObstacles Ahead9The New Input System
Two Input SystemsKeyboard and MousePressed This FrameInput ActionsRecap: Input SwapPractice on your own: Unity playground