closest 5 or so objects

is it possible to find the closest few objects to the player? if so, how would i go about it? i am using an overlap sphere but cannot seem to limit it to only a few objects…

1 Answer

1

I have a solution but you need to refit it for your purposes a bit.

      var returnarray = new Array();
      var myStoredReturns = new Array();

      returnarray = Physics.OverlapSphere (explosionPos1, radius);

      var i : int = 0;
      for(var n = 0; n < returnarray.length; n++) {

             if(returnarray[n].gameObject.name == "Warehouse Container Red"){

                     myStoredReturns *= returnarray[n]*

i++;
}
}
This code creates two variables i (simple integer) and myStoredReturns which is an array you can store your returns in. Each time the IF flags as true it will add the item to the array and move to the next index.
To limit it just to 5 indexes of myStoredReturns simply do this after the above code.
for(var p = 0; p < 5; p++) {
// Do something with each index of myStoredReturns[p] up to 5 indexes.
}
It’s not pretty but its a fairly quick and easy way to accomplish what you are looking for. Don’t forget to accept the answer if it answers your question. Thanks!
oh btw: Since overlap sphere returns a Collider, try using returnarray[n].name instead. It should match identically with the name you give the object in the inspector/scene.