修复无法点击按钮问题

This commit is contained in:
JA
2026-07-06 00:56:32 +08:00
parent 390fb99602
commit 34cf55155c
5 changed files with 88 additions and 114 deletions
+16 -21
View File
@@ -1,6 +1,5 @@
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.SceneManagement;
namespace GameFramework
{
@@ -9,33 +8,29 @@ namespace GameFramework
/// 让 EventSystem 通过 DontDestroyOnLoad 跨场景存活。
/// 这样 Gameplay、Scoring 等场景的按钮都能正常响应点击。
///
/// 场景切换时如果新场景自带 EventSystem,会自动销毁重复的那个
/// 始终保证场景中只有一个 EventSystem。
/// 修复:当场景重复加载时(如从 Scoring 回到 MainMenu
/// 销毁多余的 EventSystem,保证全局只有一个
/// </summary>
public class PersistentEventSystem : MonoBehaviour
{
void Awake()
{
// 让 EventSystem 跨场景存活
DontDestroyOnLoad(gameObject);
var allSystems = FindObjectsOfType<EventSystem>();
// 监听场景加载,清理重复的 EventSystem
SceneManager.sceneLoaded += OnSceneLoaded;
}
void OnDestroy()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
// 新场景加载后,找到所有 EventSystem,保留自己所在的,销毁其余的
var allES = FindObjectsOfType<EventSystem>();
foreach (var es in allES)
if (allSystems.Length == 0)
{
if (es.gameObject != gameObject)
Destroy(es.gameObject);
// 场景里没有 EventSystem —— 创建一个
var go = new GameObject("EventSystem");
go.AddComponent<EventSystem>();
go.AddComponent<StandaloneInputModule>();
DontDestroyOnLoad(go);
}
else
{
// 保留第一个 EventSystem,销毁重复的
DontDestroyOnLoad(allSystems[0].gameObject);
for (int i = 1; i < allSystems.Length; i++)
Destroy(allSystems[i].gameObject);
}
}
}