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 targets;
public string objectTag = "Object";
private Transform selectedObject;
void Start () {
targets = new List();
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.
↧