修改两个问题
This commit is contained in:
@@ -1,36 +1,43 @@
|
|||||||
using UnityEngine;
|
using UnityEngine;
|
||||||
using UnityEngine.EventSystems;
|
using UnityEngine.EventSystems;
|
||||||
|
using UnityEngine.SceneManagement;
|
||||||
|
|
||||||
namespace GameFramework
|
namespace GameFramework
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// 挂到 MainMenu 场景的 EventSystem 上(或和它同一个空物体上),
|
/// 全局唯一的 EventSystem 管理器。
|
||||||
/// 让 EventSystem 通过 DontDestroyOnLoad 跨场景存活。
|
/// 挂到 MainMenu 场景的 EventSystem 上,让它 DontDestroyOnLoad 跨场景存活。
|
||||||
/// 这样 Gameplay、Scoring 等场景的按钮都能正常响应点击。
|
/// 每次新场景加载时自动检测并销毁多余的 EventSystem,保证全局只有一个。
|
||||||
///
|
|
||||||
/// 修复:当场景重复加载时(如从 Scoring 回到 MainMenu),
|
|
||||||
/// 销毁多余的 EventSystem,保证全局只有一个。
|
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class PersistentEventSystem : MonoBehaviour
|
public class PersistentEventSystem : MonoBehaviour
|
||||||
{
|
{
|
||||||
void Awake()
|
void Awake()
|
||||||
{
|
{
|
||||||
var allSystems = FindObjectsOfType<EventSystem>();
|
DontDestroyOnLoad(gameObject);
|
||||||
|
CleanupDuplicates();
|
||||||
|
|
||||||
if (allSystems.Length == 0)
|
// 监听场景加载,每次新场景进来都清理一次
|
||||||
{
|
SceneManager.sceneLoaded += OnSceneLoaded;
|
||||||
// 场景里没有 EventSystem —— 创建一个
|
|
||||||
var go = new GameObject("EventSystem");
|
|
||||||
go.AddComponent<EventSystem>();
|
|
||||||
go.AddComponent<StandaloneInputModule>();
|
|
||||||
DontDestroyOnLoad(go);
|
|
||||||
}
|
}
|
||||||
else
|
|
||||||
|
void OnDestroy()
|
||||||
{
|
{
|
||||||
// 保留第一个 EventSystem,销毁重复的
|
SceneManager.sceneLoaded -= OnSceneLoaded;
|
||||||
DontDestroyOnLoad(allSystems[0].gameObject);
|
}
|
||||||
for (int i = 1; i < allSystems.Length; i++)
|
|
||||||
Destroy(allSystems[i].gameObject);
|
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
|
||||||
|
{
|
||||||
|
CleanupDuplicates();
|
||||||
|
}
|
||||||
|
|
||||||
|
void CleanupDuplicates()
|
||||||
|
{
|
||||||
|
var allSystems = FindObjectsOfType<EventSystem>();
|
||||||
|
foreach (var es in allSystems)
|
||||||
|
{
|
||||||
|
// 保留自己,销毁其他 EventSystem
|
||||||
|
if (es.gameObject != gameObject)
|
||||||
|
Destroy(es.gameObject);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user