Ine*_*pid 1 c# unity-game-engine
我想得到最远的物体的位置,它与其前面的其他物体具有相同的名称.我做了一个简单的图片来说明我的问题:

我发现了关于RaycastAll但由于某种原因我无法获得感兴趣对象的位置.
根据您获取所匹配名称的位置以及确定光线原点的方式,以下内容适合您.这假设光线由运行此方法的GameObject投射,并充当光线的原点和要匹配的名称.
public void GetFurthestObject()
{
    // Replace this with whatever you want to match with
    string nameToMatch = transform.name;
    // Initialize the ray and raycast all. Change the origin and direction to what you need.
    // This assumes that this method is being called from a transform that is the origin of the ray.
    Ray ray = new Ray(transform.position, transform.forward);
    RaycastHit[] hits;
    hits = Physics.RaycastAll(ray, float.MaxValue);
    // Initialize furthest values
    float furthestDistance = float.MinValue;
    GameObject furthestObject = null;
    // Loop through all hits
    for (int i = 0; i < hits.Length; i++)
    {
        // Skip objects whose name doesn't match.
        if (hits[i].transform.name != nameToMatch)
            continue;
        // Get the distance of this hit with the transform
        float currentDistance = Vector3.Distance(hits[i].transform.position, transform.position);
        // If the distance is greater, store this hit as the new furthest
        if (currentDistance > furthestDistance)
        {
            furthestDistance = currentDistance;
            furthestObject = hits[i].transform.gameObject;
        }
    }
}