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

Unity中如何更新存储GameObject与距离的KeyValuePair列表并动态新增元素?

解决List动态更新与新增的问题

我完全理解你选择List<KeyValuePair<GameObject, float>>的原因——普通字典虽然查找快,但面对持续变化的内容,用列表来动态维护确实更灵活。不过用这种结构做实时更新和新增时,有几个容易踩的坑,我给你梳理下正确的实现方式和常见问题排查:

1. 正确更新列表中已有对象的距离值

首先要注意:KeyValuePair<TKey, TValue>是不可变的值类型,你没法直接修改它的Value属性,必须重新创建一个新的键值对替换列表里的原有项。在Update中可以这么写:

// 假设target是你用来计算距离的参考对象
for (int i = 0; i < planesFilled.Count; i++)
{
    var currentPair = planesFilled[i];
    // 跳过已销毁的对象,避免空引用错误
    if (currentPair.Key == null) continue;
    
    // 计算最新距离
    float updatedDistance = Vector3.Distance(currentPair.Key.transform.position, target.transform.position);
    // 替换列表中的旧键值对
    planesFilled[i] = new KeyValuePair<GameObject, float>(currentPair.Key, updatedDistance);
}

2. 检测并添加新生成的对象

当新的GameObject生成后,你需要先检查列表中是否已经存在该对象,避免重复添加:

// 假设newPlane是刚生成的目标对象
bool isPlaneAlreadyInList = planesFilled.Any(pair => pair.Key == newPlane);
if (!isPlaneAlreadyInList)
{
    float initialDistance = Vector3.Distance(newPlane.transform.position, target.transform.position);
    planesFilled.Add(new KeyValuePair<GameObject, float>(newPlane, initialDistance));
}

另外,别忘了定期清理列表中已销毁的对象,不然会积累大量空引用:

// 可以在Update开头或者FixedUpdate中执行
planesFilled.RemoveAll(pair => pair.Key == null);

3. 常见错误排查

  • 空引用异常:大概率是列表中存在已被销毁的GameObject,或者参考对象target未赋值,记得先做null检查
  • 距离值不更新:别直接修改currentPair.Value——因为KeyValuePair是值类型,你修改的只是临时变量,不会影响列表里的内容,必须替换整个键值对
  • 性能卡顿:如果列表对象数量很多,Update里频繁遍历会有性能压力。这种情况下可以考虑字典+列表结合:用字典快速查找对象是否存在,用列表来遍历更新距离,兼顾查找效率和遍历灵活性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:53:47