Unity技术问题:获取场景EventSystem对象及组件失败,GetComponentInChildren返回空
Unity中GetComponentInChildren无法获取EventSystem的问题解决
问题描述
脚本挂载在GameNotes GameObject上,运行后通过GetComponentInChildren<EventSystem>(true)获取到的myEventSystem为null,需要同时获取EventSystem的GameObject及其组件。
原因排查与解决方法
确认子物体层级关系:
GetComponentInChildren仅查找当前物体的直接或间接子物体,需确保EventSystem确实是GameNotes的子物体(包括嵌套子物体)。调整代码执行顺序:原代码中先调用
DontDestroyOnLoad将物体移至特殊场景,可能导致子物体查找异常。可先获取组件再处理持久化:private EventSystem myEventSystem; public static GameNotes Instance { get; private set; } private string savePath; private void Awake() { if (Instance == null) { // 优先获取子物体组件 myEventSystem = GetComponentInChildren<EventSystem>(true); Instance = this; DontDestroyOnLoad(gameObject); savePath = Path.Combine(Application.persistentDataPath, "notes.txt"); LoadFromFile(); } else { Destroy(gameObject); } }使用全局查找备选:若场景中仅存在一个EventSystem,可直接全局查找(注意性能损耗):
myEventSystem = FindObjectOfType<EventSystem>(true); // 获取对应的GameObject:myEventSystem?.gameObject手动绑定引用(最可靠):在Inspector面板中直接将EventSystem组件拖入脚本的
myEventSystem字段,无需运行时查找:[SerializeField] private EventSystem myEventSystem;绑定后可直接通过
myEventSystem获取组件,通过myEventSystem.gameObject获取对应的GameObject。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

