Files
gold_dolphin/unity/Assets/UI/PersistentEventSystem.cs
T
2026-07-06 00:56:32 +08:00

38 lines
1.3 KiB
C#

using UnityEngine;
using UnityEngine.EventSystems;
namespace GameFramework
{
/// <summary>
/// 挂到 MainMenu 场景的 EventSystem 上(或和它同一个空物体上),
/// 让 EventSystem 通过 DontDestroyOnLoad 跨场景存活。
/// 这样 Gameplay、Scoring 等场景的按钮都能正常响应点击。
///
/// 修复:当场景重复加载时(如从 Scoring 回到 MainMenu),
/// 销毁多余的 EventSystem,保证全局只有一个。
/// </summary>
public class PersistentEventSystem : MonoBehaviour
{
void Awake()
{
var allSystems = FindObjectsOfType<EventSystem>();
if (allSystems.Length == 0)
{
// 场景里没有 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);
}
}
}
}