Source file unity-csharp/scene-flow/PauseMenu.cs from the GDnD code examples. Download raw file

// GDnD wiki example
// Demonstrates: pausing with Time.timeScale and a pause panel (Input System package, Unity 6 default)
// Related pages: [[unity-scene-management]], [[unity-input]]
 
using UnityEngine;
using UnityEngine.InputSystem;
 
public class PauseMenu : MonoBehaviour
{
    [SerializeField] private GameObject pausePanel;
 
    public bool IsPaused { get; private set; }
 
    private void Start()
    {
        // Only hide the panel. Time.timeScale is deliberately not reset here,
        // so the README experiment can show what happens when nobody resets it.
        IsPaused = false;
        if (pausePanel != null)
        {
            pausePanel.SetActive(false);
        }
    }
 
    private void Update()
    {
        // Update still runs while timeScale is 0, so the key can unpause.
        Keyboard keyboard = Keyboard.current;
        if (keyboard != null && keyboard.escapeKey.wasPressedThisFrame)
        {
            TogglePause();
        }
    }
 
    // Also wire this to a Pause or Resume button's On Click ().
    public void TogglePause()
    {
        IsPaused = !IsPaused;
        Time.timeScale = IsPaused ? 0f : 1f;
 
        if (pausePanel != null)
        {
            pausePanel.SetActive(IsPaused);
        }
    }
}