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

Unity3D C#:跨脚本调用方法时解决对象引用错误

解决“weaponAttack未设置为对象的实例”空引用错误的方法

这个错误的核心是AnimationEventManager脚本中的weaponAttack变量没有指向任何实际存在的WeaponAttack组件实例,调用其方法时触发了空引用异常。以下是具体解决方法:

  • 手动在Inspector赋值

    1. 先确保AnimationEventManager脚本中已声明weaponAttack变量,修改脚本添加:
      // 可以设为public,或用[SerializeField]保持私有但在Inspector可见
      public WeaponAttack weaponAttack;
      
    2. 选中挂载AnimationEventManager的GameObject,在Inspector面板找到该脚本组件
    3. 将场景中挂载了WeaponAttack的对象拖到weaponAttack变量的赋值框中
  • 通过代码自动获取赋值
    根据两个脚本的挂载位置,在AnimationEventManager的Awake或Start方法中添加自动获取逻辑:

    • 同对象挂载:
      void Awake()
      {
          weaponAttack = GetComponent<WeaponAttack>();
      }
      
    • WeaponAttack在子对象:
      void Awake()
      {
          weaponAttack = GetComponentInChildren<WeaponAttack>();
      }
      
    • 场景中唯一实例:
      void Awake()
      {
          weaponAttack = FindObjectOfType<WeaponAttack>();
      }
      
  • 检查动画事件的绑定对象
    确认动画事件调用的是正确对象的方法:

    1. 打开动画剪辑的Event编辑界面
    2. 检查每个事件的Receiver字段,确保选择的是已正确赋值weaponAttack的AnimationEventManager所在GameObject

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 07:09:19