Joh
Joh

Reputation: 337

Detecting Furthest Object With Similar Name

I want to get the position of the furthest object which has the same name as other objects infront of it. I made a simple picture to illustrate my problem: enter image description here

I found out about RaycastAll but for some reason I can't get the position of the object of interest.

Upvotes: 1

Views: 90

Answers (1)

hanoldaa
hanoldaa

Reputation: 616

Depending on where you are getting the name that you are matching for, and how you are determining the ray origin, the following should work for you. This assumes that the ray is being cast by a GameObject running this method and acts as the origin of the ray and the name to match.

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;
        }
    }
}

Upvotes: 5

Related Questions