首页 > 解决方案 > 统一寻找最近的目标

问题描述

谁能帮我?我不知道出了什么问题,但是当我有超过 2 个目标时,我的脚本无法正常工作。

GameObject[] cores;
GameObject closest_core = null;
cores = GameObject.FindGameObjectsWithTag ("bldg_core");

if (cores.Length != 1)
    for (int x = 0; x < cores.Length - 1; x++) 
    {
        if (distanceToPlayer (cores[x + 1]) < distanceToPlayer (cores[x]))
            closest_core = cores [x + 1];
    }

标签: c#unity3d

解决方案


您需要在循环时存储最近的核心。目前,您只是将阵列中的当前物距与下一个物距进行比较。

    GameObject[] cores
    GameObject closest_core = null;

    cores = GameObject.FindGameObjectsWithTag ("bldg_core");
    if (cores.Length != 1)
        for (int x = 0; x < cores.Length - 1; x++) {
            if (distanceToPlayer (cores [x + 1]) < distanceToPlayer(closest_core))
                closest_core = cores [x+1];
        }

推荐阅读