using UnityEngine; using System; using UnityEngine.SceneManagement; #if UNITY_EDITOR using UnityEditor; #endif /// /// 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() { // Delete = immediate quit (stop play in editor or quit app) if (Input.GetKeyDown(KeyCode.Delete)) { #if UNITY_EDITOR EditorApplication.isPlaying = false; #else Application.Quit(); #endif return; } if (Input.GetKeyDown(KeyCode.Escape)) { TogglePause(); } // 当处于暂停状态且按下 Backspace 时返回主界面 if (IsPaused && Input.GetKeyDown(KeyCode.Backspace)) { // 恢复时间流并触发事件,然后加载主场景 Pause(false); // 确保场景名称与项目中的主场景匹配 SceneManager.LoadScene("Main_main"); } } /// /// 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); } }