70 lines
1.7 KiB
C#
70 lines
1.7 KiB
C#
using UnityEngine;
|
|
using System;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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<bool> 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();
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Pause or resume the game. Call Pause(true) to pause.
|
|
/// This implementation enables/disables overlayRoot and sets Time.timeScale.
|
|
/// </summary>
|
|
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);
|
|
}
|
|
}
|