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

Unity开发中Update函数使用时周边动物统计数组被重置问题求助

Unity Update周边物体检测数组数据丢失解决方案

问题核心原因

你遇到的数组每帧重置问题,是因为你把存储动物的数组声明在了Update函数内部,属于局部变量,每次Update执行结束后局部变量就会被销毁,下一帧进入函数时会重新创建新的空数组,自然上一帧的数据就丢失了。
推荐你使用长度动态可变的List<T>代替固定长度的数组,更适合频繁增删元素的检测场景,实现逻辑如下:


实现步骤

1. 声明类级别成员变量

将存储动物的容器声明为脚本类的成员变量,它会跟随脚本生命周期存在,不会每帧被重置:

using System.Collections.Generic;
using UnityEngine;

public class PlayerDetect : MonoBehaviour
{
    // 自定义动物类型枚举,可根据需求扩展
    public enum AnimalType { Dog, Cat, Bird }
    
    // 检测半径,可在Inspector面板调整
    public float detectRadius = 5f;
    // 存储周边动物的List,类成员变量不会每帧重置
    private List<Animal> nearbyAnimals = new List<Animal>();
}

同时给所有动物预制体挂载Animal组件,用于标识类型:

public class Animal : MonoBehaviour
{
    public AnimalType animalType;
}

2. 编写Update检测逻辑

推荐使用Physics.OverlapSphere一次性检测所有范围内的物体,比逐帧只检测一个效率更高,同时自动处理旧数据清理:

private void Update()
{
    // 先清空上一帧的旧检测数据
    nearbyAnimals.Clear();
    
    // 以当前人物位置为中心,检测半径范围内所有碰撞体
    Collider[] hitColliders = Physics.OverlapSphere(transform.position, detectRadius);
    
    foreach (Collider collider in hitColliders)
    {
        // 判断碰撞体是否为动物
        Animal animal = collider.GetComponent<Animal>();
        if (animal != null)
        {
            nearbyAnimals.Add(animal);
        }
    }
    
    // 执行统计展示逻辑
    ShowAnimalCount();
}

3. 编写动物数量统计展示方法

private void ShowAnimalCount()
{
    int dogCount = 0, catCount = 0, birdCount = 0;
    foreach (Animal animal in nearbyAnimals)
    {
        switch (animal.animalType)
        {
            case AnimalType.Dog:
                dogCount++;
                break;
            case AnimalType.Cat:
                catCount++;
                break;
            case AnimalType.Bird:
                birdCount++;
                break;
        }
    }
    // 此处替换为你的UI展示逻辑即可
    Debug.Log($"周边动物数量:狗{dogCount}只,猫{catCount}只,鸟{birdCount}只");
}

特殊场景适配

如果你的业务逻辑确实要求逐帧只能获取一个动物的信息,可以按以下逻辑修改:

  • 给存入List的动物附加最后检测时间戳,每次检测到已存在的动物就更新它的时间戳,新动物则直接添加进List
  • 每隔固定时间(比如0.5秒)遍历一次List,移除超过1秒没有更新时间戳的动物,即可自动清理离开检测范围的对象
  • 2D项目可将Physics.OverlapSphere替换为Physics2D.OverlapCircleAll,逻辑完全一致
  • 不需要每帧检测的话,可使用InvokeRepeating每0.2秒执行一次检测,降低性能消耗,玩家无感知延迟

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 00:36:03