- Home /
Find closest object with tag
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?
Answer by AlwaysSunny · Oct 25, 2014 at 01:01 PM
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[i] = (objects[i].transform.position - origin).sqrMagnitude;
}
System.Array.Sort( distances, objects );
}
Thank you so much for your answer. I haven't tried it yet, but I will when I get the time :)
How do I pass the game objects?
I get two errors:
error CS1620: Argument #1' is missing
ref' modifier
And:
error CS1502: The best overloaded method match for `FindClosest.SortDistances(ref UnityEngine.GameObject[], UnityEngine.Vector3)' has some invalid arguments
When passing the argument, it needs a ref modifier, like so:
SortDistances( ref myCollection, someOrigin );
Good luck! :)
Answer by kdubnz · Oct 25, 2014 at 09:32 PM
Have a look at: http://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html
GameObject FindClosestEnemy() {
//...
}
Regards,
How do I find the closest transform of:
public GameObject test;
public Transform[] nodes;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
nodes = test.GetComponentsInChildren<Transform>();
nodes [0] = nodes [nodes.Length - 1];
}
Your answer
Follow this Question
Related Questions
Find children of object and store in an array 3 Answers
Remove first element of array 1 Answer
Find closest transform 1 Answer
Closest array element 1 Answer
Particle System Delay 0 Answers