public class GetNearestObJ : MonoBehaviour
{
/// <summary>
/// 返回最近的物体
/// </summary>
/// <param name="Source">中心物体本身</param>
/// <param name="DestObjects">所查找的物体数组</param>
/// <returns></returns>
GameObject GetNearestGameObject(GameObject Source,GameObject [] DestObjects)
{
//第一个物体
GameObject Nearest = DestObjects[0];
//与第一个物体的距离作为最短距离
float shortestDistance = Vector3.Distance(Source.transform.position, DestObjects[0].transform.position);
//循环所有物体
foreach (GameObject Obj in DestObjects )
{
float Distance = Vector3.Distance(Source.transform.position, Obj.transform.position);
if(Distance <shortestDistance)
{
Nearest = Obj;
shortestDistance = Distance;
}
}
return Nearest;
}
}
|