Menu
CoddyTech

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 icon

Challenge

Medium

Give the tennis court a pause menu. The scene wires the Pause and Resume buttons.

  1. In PauseMenu.cs, Pause() sets Time.timeScale = 0f; and calls panel.SetActive(true);.
  2. Resume() sets Time.timeScale = 1f; and calls panel.SetActive(false);.
  3. In BallMachine.cs, add if (Time.timeScale == 0f) return; above the Space check in Update().

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

Practice on your own: Unity playground