# Reach Objects in Array

hi!
i want to let collided gameobjects follow the player, but in different distances. so the first collided should follow the player with a distance of 10, the second with a distance of 11, the third with a distance of 12 and so on. in the game it is not clear which gameobject the player collides first, so i make a array that it will order the objects in the order the player collided them. now i want to reach the first object in the array through the script to tell it to follow the player with a distance of 10, then i want to reach the second object in the array to tell it to follow the player with a distance of 11 and so on.
here is my script so far. it is attached to the objects the player will collide with. but it does not work, it says in the console: ArgumentOutOfRangeException: Index is less than 0 or more than or equal to the list count.
thank you so much!

var collided : Transform;

var player : Transform;

var foundObjects = new Array();

function OnCollisionEnter (hit : Collision)
{
if(hit.gameObject.tag == “Player”)
{
}

}

function Update ()
{
var speed : float = 10;
var distance : float = Vector3.Distance(collided.transform.position, player.transform.position);

``````var firstFound = foundObjects[0];
var secondFound = foundObjects[1];
var thirdFound = foundObjects[2];

for (firstFound in foundObjects)
{
if (distance > 10)
{
collided.LookAt(player);
collided.Translate(speed*Vector3.forward*Time.deltaTime);
}
else
{
speed = 0;
}
}
for (secoundFound in foundObjects)
{
if (distance > 11)
{
collided.LookAt(player);
collided.Translate(speed*Vector3.forward*Time.deltaTime);
}
else
{
speed = 0;
}
}
for (secoundFound in foundObjects)
{
if (distance > 12)
{
collided.LookAt(player);
collided.Translate(speed*Vector3.forward*Time.deltaTime);
}
else
{
speed = 0;
}
}
``````

}

``````var firstFound = foundObjects[0];
var secondFound = foundObjects[1];
var thirdFound = foundObjects[2];
``````

It is very bad form to reference items in an array by index without knowing for certain there are items in the array. Your code could easily be condensed into a single for loop, like so:

``````for(var i = 0; i < foundObjects.length; i++) {
if(i > 3) return; //only if you really want to limit them to 3 items only, change this number to increase the number of things that can follow you
for (var found in foundObjects) {
if (distance > 10 + i) //10 + i starts at 0, so the speed goes from 10, up by 1 each time
{
collided.LookAt(player);
collided.Translate(speed*Vector3.forward*Time.deltaTime);
}
else
{
speed = 0;
}
}
}
``````

I’m also concerned that the items you’re finding in your loops (firstFound, secondFound etc) aren’t actually being used inside the loop, indeed, you’re only referencing collided in each loop. You might want to look into the implimentation for that next. But your out-of-range exception is coming from the fact you’re not checking to see if foundObjects[0], [1] and [2] actually contain something.