How do I find the closest object with a certain tag?
Say, if I have 4 cubes, all with the same tag. How do I find the closest of the 4 cubes?
How do I find the closest object with a certain tag?
Say, if I have 4 cubes, all with the same tag. How do I find the closest of the 4 cubes?
Have a look at:
GameObject FindClosestEnemy() {
//...
}
Regards,
Senior programmers, please don’t think too badly of me for this messy method. MrMelonPie, this ought to sort a collection of GameObjects by their distance from a specified origin:
Get your collection with FindObjectsWithTag, then call SortDistances, using the collection as the first argument, and the source point as the second. The first (or last, I don’t actually recall presently) element of the collection will be the nearest.
public static void SortDistances( ref GameObject[] objects, Vector3 origin ) {
float[] distances = new float[ objects.Length ];
for (int i = 0; i < objects.Length; i++) {
distances _= (objects*.transform.position - origin).sqrMagnitude;*_
* }*
* System.Array.Sort( distances, objects );*
* }*