- Home /
distance shortest in the list
How to determine the shortest distance between the gameobjects in the list Thank you !
Answer by FlaSh-G · Jul 16, 2017 at 03:52 PM
You need to iterate over the list of GameObjects, then, for each GO, iterate over all GOs with a higher index and compare the distance. There sure is some fancy way to write this with Linq, but explicit loops will probably create a better understanding here.
var shortestDistance = Mathf.infinity;
GameObject go1;
GameObject go2;
for(var i = 0; i < myGameObjects.Length - 1; i++)
{
for(var k = i + 1; k < myGameObjects.Length; k++)
{
var distance = Vector3.Distance(myGameObjects[i].transform.position, myGameObjects[k].transform.position);
if(distance < shortestDistance)
{
shortestDistance = distance;
go1 = myGameObjects[i];
go2 = myGameObjects[k];
}
}
}
Debug.Log(go1.name + " and " + go2.name + " are closest with " + shortestDistance + "m distance.");
The outer for loop iterates over all GameObjects except the last, and the inner loop then iterates over all GameObjects that come later in the list than the GO from the outer loop. This way, you don't compare a pair of GameObjects twice.
For every pair of GameObjects, we calculate the distance between them. If that distance is shorter than the previous shortest distance, we overwrite the shortest distance and remember the two GameObjects we are looking at.
So you want to compare only to one specific object? You can make it only one loop then.
var shortestDistance = $$anonymous$$athf.infinity;
GameObject closestGO;
for(var i = 0; i < myGameObjects.Length; i++)
{
var distance = Vector3.Distance(transform.position, myGameObjects[i].transform.position);
if(distance < shortestDistance)
{
shortestDistance = distance;
closestGO = myGameObjects[i];
}
}
The list of GameObjects referenced by "myGameObjects" can be gathered any way you want. For example
var myGameObjects = GameObject.FindGameObjectsWithTag("Enemy");
But you shouldn't call that function every frame in Update.
Your answer
Follow this Question
Related Questions
How to determine the minimum distance between objects? 1 Answer
FPS Controller Minimum Movement Increasing 1 Answer
Instantiate gameobject with minimum distance from another gameobject 1 Answer
calculating vertical distance 1 Answer
code for detecting if a 2d infinite runner player stopped moving because it hit a wall or something 1 Answer