LookAt and Find closest objects by tag

As mentioned in an update of a previous question, this is a solution to a bigger problem of mine.

I would like my AI to be able to turn to face a certain object (call it Top) and find the closest object tagged “Closet” then calculate the distance between the AI and the Closet (I can handle calculating the distance on my own).

My question is, how would I go into finding the closest object tagged “Closet” in the direction that my AI is looking at?

Is it possible to achieve it without raycasting?

Any advice or throwing me in the right direction is greatly appreciated.

If you look at the example scripts for GameObject.FindGameObjectsWithTag(), the last script define a function for finding the closest enemy. Your code would be the same, with “enemy” replaced by “Closest”. To handle the “in the direction that my AI is looking at” part, you define an angle of view for “looking”. So if you say your AI can see 50 degrees, that means he can see 25 degrees on either side of his forward vector. Then at the top of the ‘for’ loop, you add:

if (Vector3.Angle(transform.forward, go.transform.position - position) > halfAngleOfView))
    continue;

This will eliminate processing any game objects that are outside the angle of view for your AI. Note the function can return null, so your code that call it must handle the situation where no object tagged “Closest” is in view.

If you put them all into a list that have the tag, then find the closest by distance. Something like this should work.

public List<Transform> targets;
public string objectTag = "Object";
private Transform selectedObject;

void Start () {
       targets = new List<Transform>();   
       myTransform = transform;
       AddAllObjects();
    }

public void AddAllObjects() {
       GameObject[] go = GameObject.FindGameObjectsWithTag(objectTag);
 
       foreach(GameObject object in go)
         AddTarget(object.transform);
    }
 
    public void AddTarget(Transform object) {
       targets.Add(object);
    }
 
    private void SortTargetsByDistance() {
       targets.Sort(delegate(Transform t1, Transform t2) { 
         return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
       });
    }

Then if you want to pick the closest use targets[0]. Put it into a transform such as

selectedObject = targets[0];

Call SortTargetsByDistance in Update or LateUpdate, or whenever you want to call it to re-sort the list. As far as looking at the object use transform.LookAt(selectedObject); you can lock certain axis if needed.