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

Unity光枪射击游戏关卡推进问题:数组移除元素报错求解

Unity复古光枪射击游戏:当前区域敌人全灭后推进关卡的解决方案

问题根源

  • 数组是固定长度的集合,无法直接移除元素,这就是你尝试移除时报错的核心原因。
  • 用全局标签判断会误统计视野外的敌人,所以必须维护当前区域内的专属敌人列表,而非全局查询。

解决方案:改用List<GameObject>动态维护敌人

List是支持动态增删的集合,完美适配当前需求。以下是修改后的完整代码:

1. 重构FightZone脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FightZone : MonoBehaviour
{
    public GameObject Starter;
    public Transform nodeLocation;
    // 替换数组为动态List,用于维护当前区域的敌人
    public List<GameObject> currentZoneEnemies = new List<GameObject>();

    void Update()
    {
        // 先清理列表中已被销毁的敌人,避免空引用问题
        currentZoneEnemies.RemoveAll(enemy => enemy == null);
        
        // 当当前区域敌人全部清除时,触发关卡推进逻辑
        if (currentZoneEnemies.Count == 0)
        {
            Instantiate(Starter, nodeLocation.position, nodeLocation.rotation);
            Destroy(gameObject);
        }
    }

    // 提供外部调用方法,将敌人加入当前区域列表
    public void AddEnemyToZone(GameObject enemy)
    {
        if (!currentZoneEnemies.Contains(enemy))
        {
            currentZoneEnemies.Add(enemy);
        }
    }
}

2. 调整EnemyHealth脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyHealth : MonoBehaviour
{
    public int startingHealth = 3;
    public int currentHealth;
    public GameObject hurtFlash;
    bool damaged;
    public FightZone FZ;

    void Awake()
    {
        currentHealth = startingHealth;
        // 敌人初始化时,自动加入所属区域的敌人列表
        if (FZ != null)
        {
            FZ.AddEnemyToZone(gameObject);
        }
    }

    void Update()
    {
        if (damaged)
        {
            Instantiate(hurtFlash, transform.position, transform.rotation);
            damaged = false;
        }
    }

    public void TakeDamage(int amount)
    {
        currentHealth -= amount;
        damaged = true;
        
        if (currentHealth <= 0)
        {
            // 先从区域列表移除当前敌人,再执行销毁
            if (FZ != null)
            {
                FZ.currentZoneEnemies.Remove(gameObject);
            }
            Destroy(gameObject);
        } 
    }
}

额外优化提示

  • 减少Update性能消耗:如果当前区域敌人数量较多,可以把列表清理和判断逻辑移到LateUpdate,或者改用事件触发(比如敌人死亡时主动通知FightZone),避免每帧遍历列表。
  • 绑定检查:确保每个敌人的FZ字段都正确绑定到当前区域的FightZone组件,防止空引用报错。
  • 动态生成适配:如果敌人是动态生成的,在生成代码里调用FightZone.AddEnemyToZone(),确保新生成的敌人被正确加入当前区域列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 01:45:25