Files
2025TapTapGameJam/Assets/Script/Gameplay/Global/ScenesManager.cs

130 lines
3.7 KiB
C#
Raw Normal View History

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using System.Collections.Generic;
using Core;
using Script.Gameplay.Input;
namespace Script.Gameplay.Global
{
public class ScenesManager : MonoSingleton<ScenesManager>
{
private string currentGameplayScene;
private bool isLoadGameplayUI = false;
// 修正:直接根据当前激活场景判断
public bool IsInMainMenu =>
currentGameplayScene == "StartMenu";
// 修正:只有当已有记录的 gameplay 场景且激活场景与之匹配时才返回 true
public bool IsInGameplay =>
currentGameplayScene == "Level1" || currentGameplayScene == "Test";
public bool IsActiveScene(string sceneName)
{
return SceneManager.GetActiveScene().name == sceneName;
}
public bool IsSceneLoaded(string sceneName)
{
return SceneManager.GetSceneByName(sceneName).isLoaded;
}
public void LoadMainMenu()
{
if (isLoadGameplayUI)
{
StartCoroutine(UnloadScene("UIScene"));
isLoadGameplayUI = false;
}
StartCoroutine(SwitchGameplay("StartMenu"));
}
public void LoadGameplay(string sceneName)
{
StartCoroutine(SwitchGameplay(sceneName));
ReLoadUIScene();
}
public void ReLoadUIScene()
{
if (isLoadGameplayUI)
{
StartCoroutine(UnloadScene("UIScene"));
}
StartCoroutine(LoadSceneAdditive("UIScene"));
isLoadGameplayUI = true;
}
private IEnumerator SwitchGameplay(string newScene)
{
if (!string.IsNullOrEmpty(currentGameplayScene))
{
yield return UnloadScene(currentGameplayScene);
}
yield return LoadSceneAdditive(newScene);
currentGameplayScene = newScene;
// 可选:将新场景设置为激活场景
SceneManager.SetActiveScene(SceneManager.GetSceneByName(newScene));
}
private IEnumerator LoadSceneAdditive(string sceneName)
{
var async = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Additive);
while (!async.isDone)
{
yield return null;
}
}
private IEnumerator UnloadScene(string sceneName)
{
var async = SceneManager.UnloadSceneAsync(sceneName);
while (!async.isDone)
{
yield return null;
}
}
public IEnumerator UnloadScenesInOrder(List<string> sceneNames)
{
foreach (var sceneName in sceneNames)
{
if (IsSceneLoaded(sceneName))
{
var async = SceneManager.UnloadSceneAsync(sceneName);
while (!async.isDone)
{
yield return null;
}
}
}
}
public void QuitGame()
{
var scenesToUnload = new List<string> { "UIScene", currentGameplayScene };
StartCoroutine(QuitAndUnload(scenesToUnload));
}
private IEnumerator QuitAndUnload(List<string> scenes)
{
yield return UnloadScenesInOrder(scenes);
// 清理 InputManager
if (InputManager.Instance != null)
{
Destroy(InputManager.Instance.gameObject);
}
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
}
}