using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using UnityEngine.InputSystem; using UnityEngine.EventSystems; using UnityEngine.InputSystem.UI; // 遊戲中按 Esc 暫停 : 時間停止、放開滑鼠,選「繼續」或「回到主畫面」 // 切出遊戲視窗 (Alt+Tab 等) 時也會自動暫停 // 暫停期間記錄器不記錄,回合照樣有效 public class PauseMenu : MonoBehaviour { [Header("UI 參照")] [Tooltip("暫停視窗 (Panel),平常隱藏")] public GameObject pausePanel; [Tooltip("繼續 Button")] public Button resumeButton; [Tooltip("回到主畫面 Button")] public Button menuButton; [Header("場景")] public string startSceneName = "StartUI"; // 給其他腳本判斷 (視角、記錄器) public static bool IsPaused { get; private set; } // 開始暫停的時間 (跟記錄器同一條時間軸) : 切出視窗時遊戲會停住,記錄器要靠這個知道真正的暫停時間 public static double PauseStartTime { get; private set; } void Start() { EnsureButtonsClickable(); if (pausePanel != null) pausePanel.SetActive(false); if (resumeButton != null) resumeButton.onClick.AddListener(Resume); if (menuButton != null) menuButton.onClick.AddListener(BackToMenu); } void Update() { if (Keyboard.current != null && Keyboard.current.escapeKey.wasPressedThisFrame) { if (IsPaused) Resume(); else Pause(); } } // 遊戲視窗失去焦點 (Alt+Tab、點到別的視窗) : 自動暫停,回來時要按「繼續」 void OnApplicationFocus(bool hasFocus) { if (!hasFocus && !IsPaused) Pause(); } void OnDestroy() { // 離開場景時一定要恢復,不然下一個場景會停住 IsPaused = false; Time.timeScale = 1f; } // 按鈕要能點,需要 : 場景裡有 EventSystem、Canvas 上有 Graphic Raycaster // 地圖場景不一定有 (例如沙漠是從 Demo 場景改的),缺的話這裡自動補上 void EnsureButtonsClickable() { if (EventSystem.current == null && FindAnyObjectByType() == null) { GameObject es = new GameObject("EventSystem"); es.AddComponent(); es.AddComponent(); } Canvas canvas = pausePanel != null ? pausePanel.GetComponentInParent(true) : null; if (canvas != null && canvas.GetComponent() == null) { canvas.gameObject.AddComponent(); } } void Pause() { IsPaused = true; PauseStartTime = Time.realtimeSinceStartupAsDouble; Time.timeScale = 0f; Cursor.lockState = CursorLockMode.None; Cursor.visible = true; if (pausePanel != null) pausePanel.SetActive(true); } void Resume() { IsPaused = false; Time.timeScale = 1f; Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; if (pausePanel != null) pausePanel.SetActive(false); } void BackToMenu() { IsPaused = false; Time.timeScale = 1f; Cursor.lockState = CursorLockMode.None; Cursor.visible = true; SceneManager.LoadScene(startSceneName); } }