From deaffb85bfa2913d3846ca37e50859336996a029 Mon Sep 17 00:00:00 2001 From: JA <1323160571@qq.com> Date: Mon, 6 Jul 2026 01:22:53 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=B8=A4=E4=B8=AA=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- unity/Assets/UI/PersistentEventSystem.cs | 47 ++++++++++++++---------- 1 file changed, 27 insertions(+), 20 deletions(-) diff --git a/unity/Assets/UI/PersistentEventSystem.cs b/unity/Assets/UI/PersistentEventSystem.cs index ac5133d..de9ac28 100644 --- a/unity/Assets/UI/PersistentEventSystem.cs +++ b/unity/Assets/UI/PersistentEventSystem.cs @@ -1,36 +1,43 @@ using UnityEngine; using UnityEngine.EventSystems; +using UnityEngine.SceneManagement; namespace GameFramework { /// - /// 挂到 MainMenu 场景的 EventSystem 上(或和它同一个空物体上), - /// 让 EventSystem 通过 DontDestroyOnLoad 跨场景存活。 - /// 这样 Gameplay、Scoring 等场景的按钮都能正常响应点击。 - /// - /// 修复:当场景重复加载时(如从 Scoring 回到 MainMenu), - /// 销毁多余的 EventSystem,保证全局只有一个。 + /// 全局唯一的 EventSystem 管理器。 + /// 挂到 MainMenu 场景的 EventSystem 上,让它 DontDestroyOnLoad 跨场景存活。 + /// 每次新场景加载时自动检测并销毁多余的 EventSystem,保证全局只有一个。 /// public class PersistentEventSystem : MonoBehaviour { void Awake() { - var allSystems = FindObjectsOfType(); + DontDestroyOnLoad(gameObject); + CleanupDuplicates(); - if (allSystems.Length == 0) + // 监听场景加载,每次新场景进来都清理一次 + SceneManager.sceneLoaded += OnSceneLoaded; + } + + void OnDestroy() + { + SceneManager.sceneLoaded -= OnSceneLoaded; + } + + void OnSceneLoaded(Scene scene, LoadSceneMode mode) + { + CleanupDuplicates(); + } + + void CleanupDuplicates() + { + var allSystems = FindObjectsOfType(); + foreach (var es in allSystems) { - // 场景里没有 EventSystem —— 创建一个 - var go = new GameObject("EventSystem"); - go.AddComponent(); - go.AddComponent(); - DontDestroyOnLoad(go); - } - else - { - // 保留第一个 EventSystem,销毁重复的 - DontDestroyOnLoad(allSystems[0].gameObject); - for (int i = 1; i < allSystems.Length; i++) - Destroy(allSystems[i].gameObject); + // 保留自己,销毁其他 EventSystem + if (es.gameObject != gameObject) + Destroy(es.gameObject); } } }