Pause with timeScale
Part of the Building Real Games section of Coddy's Unity journey. Lesson 34 of 60.
Time.timeScale is how fast game time runs: 1 is normal speed and 0 stops it. At 0, Time.deltaTime is 0, so every movement written as speed * Time.deltaTime stands still. FixedUpdate() is no longer called, so Rigidbodies hang in the air, and WaitForSeconds and Invoke wait, since they count game time. This script toggles the pause from a button whose On Click list calls TogglePause, and shows a panel while paused:
public class PauseToggle : MonoBehaviour
{
public GameObject pausePanel;
bool paused;
public void TogglePause()
{
paused = !paused;
Time.timeScale = paused ? 0f : 1f;
pausePanel.SetActive(paused);
}
}Not everything stops. Update() and LateUpdate() are still called every frame, with Time.deltaTime at 0, a coroutine's yield return null still comes back the next frame, and the UI still takes clicks, which is how the button can end the pause. Keys are still read too: a frog that jumps on Space in Update() would take the press during the pause and leap on the first physics step after it. Its script skips the keys while time stands still:
void Update()
{
if (Time.timeScale == 0f) return; // paused: ignore the keys
if (Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector3.up * jump, ForceMode.Impulse);
}
}Time.timeScale belongs to the whole game, not to a scene: load another scene while it is 0 and the new scene starts paused. A menu button that restarts or quits a level sets it back to 1 first.
Challenge
MediumGive the tennis court a pause menu. The scene wires the Pause and Resume buttons.
- In
PauseMenu.cs,Pause()setsTime.timeScale = 0f;and callspanel.SetActive(true);. Resume()setsTime.timeScale = 1f;and callspanel.SetActive(false);.- In
BallMachine.cs, addif (Time.timeScale == 0f) return;above the Space check inUpdate().
Press Play, serve a ball and pause: it hangs in mid-air. Then Check.
Try it yourself
using UnityEngine;
public class PauseMenu : MonoBehaviour
{
public GameObject panel;
public void Pause()
{
// Stop game time and show the panel
}
public void Resume()
{
// Game time at normal speed again, panel hidden
}
}
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