104 lines
2.8 KiB
C#
104 lines
2.8 KiB
C#
using UnityEngine;
|
||
using System;
|
||
using System.Collections;
|
||
using UnityEngine.SceneManagement;
|
||
#if UNITY_EDITOR
|
||
using UnityEditor;
|
||
#endif
|
||
|
||
/// <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()
|
||
{
|
||
// 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);
|
||
// ȷ��������������Ŀ�е�������ƥ��
|
||
StartCoroutine(LoadSceneAsync("Main_main"));
|
||
}
|
||
}
|
||
|
||
/// <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);
|
||
}
|
||
|
||
private IEnumerator LoadSceneAsync(string sceneName)
|
||
{
|
||
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName);
|
||
while (!asyncLoad.isDone)
|
||
{
|
||
yield return null;
|
||
}
|
||
}
|
||
}
|