提问者:小点点

如何在统一中找到数组中第二接近的对象?[重复]


我在团结中挣扎。我想创建一个脚本,能够找到离玩家最近的对象(我设法做到了),以及离玩家第二近的对象。我的问题是如何修改此代码,使其也适用于第二个对象?

public class Robot2 : MonoBehaviour
{
    public GameObject cameraHolder;
    public Transform[] objects;
    private Transform nearestObj;
    private Transform secondObj;
    void Update()
    {
        float lowestDist = Mathf.Infinity;
        nearestObj = null;
        secondObj = null;
    
        foreach(Transform obj in objects)
        {
            float dist = Vector3.Distance(transform.position, obj.position);
            if(dist < lowestDist)
            {
                lowestDist = dist;
                nearestObj = obj;
            }
        } 
        Debug.DrawLine(transform.position, nearestObj.transform.position, Color.red); 
        cameraHolder.transform.position = nearestObj.transform.position;
    }
}

共2个答案

匿名用户

你可以像下面的代码一样使用LINQ:

Objects.ToList().OrderBy(o => Vector3.Distance(transform.position, o.position))[1]

或者

Objects.ToList().OrderByDescending(o => Vector3.Distance(transform.position, o.position))[1]

匿名用户

您可以这样做:

float lowestDistance = Mathf.Infinity;
float nextLowestDistance = Mathf.Infinity;
nearestObject = null;
secondObject = null;

foreach ( Transform object in objects )
{
    float dist = Vector3.Distance( object.position, transform.position );
    if ( dist < lowestDistance )
    {
        if ( lowestDistance < nextLowestDistance )
        {
            nextLowestDistance = lowestDistance;
            secondObject = nearestObject;
        }
        lowestDistance = dist;
        nearestObject = object;
    }
    else if ( dist < nextLowestDistance )
    {
       nextLowestDistance = dist;
       secondObject = object;
    }
}