Unity按Q触发医疗包动画时出现Object reference not set to an instance of an object错误
问题原因分析
你遇到的Object reference not set to an instance of an object报错,是代码中声明的Animator类型变量anim未被赋值,运行时为null,调用SetBool方法时触发了空引用异常。
修复步骤
- 第一步:在脚本的
Start生命周期方法中添加获取Animator组件的逻辑,同时增加非空校验方便后续排查问题:
void Start() { // 从当前挂载脚本的GameObject上获取Animator组件 anim = GetComponent<Animator>(); if(anim == null) { Debug.LogError("当前物体上未找到Animator组件!", gameObject); } }
- 第二步:确认挂载该脚本的GameObject上已经添加了Animator组件,并且Animator Controller中已经创建了名为
Qpress的Bool类型参数,动画状态切换的条件配置正确。 - 第三步:如果Animator组件没有挂载在当前脚本所在的物体上,需要对应修改获取组件的方法:
- 子物体获取:
anim = GetComponentInChildren<Animator>(); - 父物体获取:
anim = GetComponentInParent<Animator>();
- 子物体获取:
修复后完整代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Anim_Trigger_for_healthpack : MonoBehaviour { private Coroutine onHealKit = null; private Animator anim; void Start() { anim = GetComponent<Animator>(); if(anim == null) { Debug.LogError("未找到Animator组件,请检查挂载配置", gameObject); } } void Update() { if (Input.GetKeyDown(KeyCode.Q)) { // 增加anim非空判断,避免组件缺失时按下Q报错 if (onHealKit == null && anim != null) onHealKit = StartCoroutine(HealthKit()); } } IEnumerator HealthKit() { anim.SetBool("Qpress", true); yield return new WaitForSeconds(2.0f); anim.SetBool("Qpress", false); onHealKit = null; } }
内容的提问来源于stack exchange,提问作者Arya Akhavein
相关产品推荐
相关产品推荐

