首页 > 解决方案 > 检测具有相似名称的最远对象

问题描述

我想获得与它前面的其他对象同名的最远对象的位置。我做了一张简单的图片来说明我的问题: 在此处输入图像描述

我发现了 RaycastAll,但由于某种原因,我无法获得感兴趣对象的位置。

标签: c#unity3d

解决方案


根据您从哪里获得要匹配的名称,以及您如何确定光线来源,以下内容应该适合您。这假设射线由运行此方法的 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;
        }
    }
}

推荐阅读