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

调用脚本void方法触发NullReferenceException问题排查

Unity脚本调用Item.Use方法触发空引用异常问题及解决

问题场景

编写Unity脚本时,尝试调用Item类对象的Use方法,代码如下:

Debug.Log($"{obj.transform.GetChild(1).gameObject.name}, {other_obj.name}"); //运行正常

obj.transform.GetChild(1).gameObject.GetComponent<Item>(); //运行正常

obj.transform.GetChild(1).gameObject.GetComponent<Item>().Use(other_obj.tag, other_obj); //触发NullReferenceException

排查细节

  • 单独获取Item组件的代码执行无异常,但调用Use方法时直接触发NullReferenceException
  • 已确认other_obj不为空,可正常输出其name属性
  • 曾怀疑Use方法内部存在问题,在方法开头添加Debug.Log("use")调试代码,但未打印任何信息,说明方法并未执行

问题解决

更新:问题已解决!感谢derHugo,原因是obj.transform.GetChild(1).gameObject.GetComponent<Item>()实际返回null,导致调用Use方法时触发空引用。

内容的提问来源于stack exchange,提问作者Simone Bernardini

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 23:15:53