You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 03:37:24