43 lines
1.3 KiB
C#
43 lines
1.3 KiB
C#
using UnityEngine;
|
|
using UnityEngine.EventSystems;
|
|
using UnityEngine.SceneManagement;
|
|
|
|
namespace GameFramework
|
|
{
|
|
/// <summary>
|
|
/// 挂到 MainMenu 场景的 EventSystem 上(或和它同一个空物体上),
|
|
/// 让 EventSystem 通过 DontDestroyOnLoad 跨场景存活。
|
|
/// 这样 Gameplay、Scoring 等场景的按钮都能正常响应点击。
|
|
///
|
|
/// 场景切换时如果新场景自带 EventSystem,会自动销毁重复的那个,
|
|
/// 始终保证场景中只有一个 EventSystem。
|
|
/// </summary>
|
|
public class PersistentEventSystem : MonoBehaviour
|
|
{
|
|
void Awake()
|
|
{
|
|
// 让 EventSystem 跨场景存活
|
|
DontDestroyOnLoad(gameObject);
|
|
|
|
// 监听场景加载,清理重复的 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 (es.gameObject != gameObject)
|
|
Destroy(es.gameObject);
|
|
}
|
|
}
|
|
}
|
|
}
|