一大波优化
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.EventSystems;
|
||||
using UnityEngine.SceneManagement;
|
||||
|
||||
namespace GameFramework
|
||||
{
|
||||
@@ -8,25 +9,34 @@ namespace GameFramework
|
||||
/// 让 EventSystem 通过 DontDestroyOnLoad 跨场景存活。
|
||||
/// 这样 Gameplay、Scoring 等场景的按钮都能正常响应点击。
|
||||
///
|
||||
/// 如果场景里没有 EventSystem,也可以挂到任意空物体上,
|
||||
/// 脚本会自动创建一个。
|
||||
/// 场景切换时如果新场景自带 EventSystem,会自动销毁重复的那个,
|
||||
/// 始终保证场景中只有一个 EventSystem。
|
||||
/// </summary>
|
||||
public class PersistentEventSystem : MonoBehaviour
|
||||
{
|
||||
void Awake()
|
||||
{
|
||||
// 如果场景里没有 EventSystem,自动创建
|
||||
if (FindObjectOfType<EventSystem>() == null)
|
||||
{
|
||||
var go = new GameObject("EventSystem");
|
||||
go.AddComponent<EventSystem>();
|
||||
go.AddComponent<StandaloneInputModule>();
|
||||
}
|
||||
|
||||
// 让 EventSystem 跨场景存活
|
||||
var eventSystem = FindObjectOfType<EventSystem>();
|
||||
if (eventSystem != null)
|
||||
DontDestroyOnLoad(eventSystem.gameObject);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user