using UnityEngine; using System; /// /// Simple pause manager. Call Pause(true) to pause or Pause(false) to resume. /// - overlayRoot: GameObject that will be enabled when paused and disabled when resumed. /// - Pressing Escape toggles pause while the manager exists. /// public class PauseManager : MonoBehaviour { public static PauseManager Instance { get; private set; } [Header("Overlay")] public GameObject overlayRoot; // object to enable/disable on pause public bool IsPaused { get; private set; } = false; // 添加暂停状态改变事件 public event Action OnPauseStateChanged; void Awake() { if (Instance == null) Instance = this; else Destroy(gameObject); } void Start() { if (overlayRoot != null) overlayRoot.SetActive(false); } void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { TogglePause(); } } /// /// Pause or resume the game. Call Pause(true) to pause. /// This implementation enables/disables overlayRoot and sets Time.timeScale. /// public void Pause(bool pause) { if (pause) { if (IsPaused) return; if (overlayRoot != null) overlayRoot.SetActive(true); Time.timeScale = 0f; IsPaused = true; OnPauseStateChanged?.Invoke(true); } else { if (!IsPaused) return; if (overlayRoot != null) overlayRoot.SetActive(false); Time.timeScale = 1f; IsPaused = false; OnPauseStateChanged?.Invoke(false); } } public void TogglePause() { Pause(!IsPaused); } }