# For each GameObject in array calculate distance

I can’t seem to figure out how to calculate distance for every GameObject in array, because the size will vary, depending on how many there are in each wave. Here is my code:

``````var closestEnemy : GameObject[];

var followSpeed : float = 2;

private var isAttacking : boolean;

function FixedUpdate ()
{
closestEnemy = GameObject.FindGameObjectsWithTag("Enemy");
System.Array.Sort(closestEnemy, distanceComparison);

if(isAttacking == false)
{
Follow();
}
}

private function distanceComparison ()
{
var firstClosestEnemy = Vector3.Distance(transform.position, closestEnemy[0].transform.position);
var secondClosestEnemy = Vector3.Distance(transform.position, closestEnemy[1].transform.position);

return firstClosestEnemy.CompareTo(secondClosestEnemy);
}

{
transform.position = Vector3.MoveTowards(transform.position, closestEnemy[0].transform.position, followSpeed * Time.deltaTime);
}

function OnCollisionEnter (coll : Collision)
{
if(coll.gameObject.Tag == "Player")
{
coll.SendMessage("TakeDamage", 10.0);
}
}

function TakeDamage (damage : float)
{
GetComponent("Health").health -= damage;
}
``````

This can only calculate the distance of 2 gameobjects and compare them, but I want it to calculate the distance for every object. Thank you for helping!

Edit:

Is this more like what you wanted? This will loop through all of your enemies and detect which one is closes to the player, then print it to console.

``````var enemyList : GameObject[];
var player : Transform;

function Update () {
Debug.Log(DistanceComparison());
}

function DistanceComparison(){
var distanceFromPlayer : float;
var previousDistance : float;
var closestEnemy : GameObject;

for(var enemy : GameObject in enemyList){
Debug.Log(enemy.name);
distanceFromPlayer = Vector3.Distance(player.transform.position,enemy.transform.position);
if(distanceFromPlayer<previousDistance || previousDistance == 0){
previousDistance = distanceFromPlayer;
closestEnemy = enemy;

}
}
return closestEnemy;
}
``````

If you wanted this to detect how far every enemy is away from every other enemy you will need to put in another for loop inside of the for loop that is already there.