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

Unity中检查Inspector引用对象缺失?宝箱显示异常排查

问题分析与解决方案

原脚本的核心Bug

你的代码存在致命逻辑错误:在Update方法中,只要num不等于敌人总数,就会执行num = 0重置计数。这意味着每帧统计完死亡敌人数量后,除非刚好所有敌人都死了,否则计数会被清零,永远触发不了宝箱显示的条件。

修复后的代码

把num = 0的位置移到Fight方法开头,每帧统计前先重置计数,而非在判断不满足条件时清零:

public class FinalFight : MonoBehaviour
{
    public GameObject[] enemies;
    private int num = 0;
    private bool fightStarts = true;
    private bool fightOver = false;

    void Update()
    {
        if (fightStarts && !fightOver)
        {
            Fight();
            if (num == enemies.Length)
            {
                this.gameObject.SetActive(true);
                fightOver = true;
            }
        }
    }

    public void Fight()
    {
        num = 0; // 统计前先重置计数
        for (int i = 0; i < enemies.Length; i++)
        {
            if (enemies[i] == null)
            {
                num++;
            }
        }
    }
}

其他更可靠的敌人状态检查方法

  • 检查对象激活状态:如果敌人死亡后不是直接销毁,而是设置为非激活状态,用!enemies[i].activeSelf判断更稳妥,能避免销毁后数组元素变为Missing的问题:
    if (!enemies[i].activeSelf) num++;
    
  • 通过敌人组件状态判断:给敌人添加死亡标记组件(比如EnemyHealth),通过组件内的isDead字段判断,无需依赖对象是否销毁:
    // 假设EnemyHealth脚本里有public bool isDead;
    EnemyHealth enemyHealth = enemies[i].GetComponent<EnemyHealth>();
    if (enemyHealth != null && enemyHealth.isDead) num++;
    
  • 监听死亡事件:让敌人死亡时主动发送事件,宝箱脚本订阅事件并计数,无需每帧遍历数组,性能更优:
    // 敌人脚本中
    public event Action OnEnemyDead;
    void Die()
    {
        OnEnemyDead?.Invoke();
        // 其他死亡逻辑
    }
    
    // 宝箱脚本中
    private int deadCount = 0;
    void Start()
    {
        foreach(var enemy in enemies)
        {
            enemy.GetComponent<Enemy>().OnEnemyDead += () => 
            {
                deadCount++;
                if(deadCount == enemies.Length)
                {
                    gameObject.SetActive(true);
                    fightOver = true;
                }
            };
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 08:23:59