我有这个脚本来找到当前最接近的立方体:
GameObject FindClosestCube() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("cube");
GameObject closest = null;
float distance = Mathf.Infinity;
float position = transform.position.z;
foreach (GameObject go in gos) {
float diff = go.transform.position.z - position;
float curDistance = diff;
if (curDistance < distance) {
closest = go;
distance = curDistance;
}
}
return closest;
}
现在我想获得第二个最接近的立方体,所以最接近立方体(z轴)后面的最近立方体。我尝试了一些东西,但它们没有用,所以有人可以解释一下如何实现这个目标吗?感谢。
答案 0 :(得分:2)
在指定新的最近值之前,将最接近的当前值分配给最接近的第二个。 然后返回一个游戏对象数组,第一个元素是最接近的。
GameObject[] FindClosestCubes() {
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("cube");
GameObject closest = null;
GameObject secondClosest = null;
float distance = Mathf.Infinity;
float position = transform.position.z;
foreach (GameObject go in gos) {
float diff = go.transform.position.z - position;
float curDistance = diff;
if (curDistance < distance) {
secondClosest = closest;
closest = go;
distance = curDistance;
}
}
return new GameObject[] { closest, secondClosest };
}