- Home /
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...
Answer by AngryMarine · Aug 29, 2011 at 08:54 AM
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[i] = 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.
thisDistance and range are simple Float vars. Give it a shot building your list of nearest 5 and if you need help I'll check up on ya.
i think its because im an idiot, but i cant manage to make it work... i cant make it limit it to 5, its either everything, or the script wont pick anything. Heres my code:
var returnarray = new Array();
returnarray = Physics.OverlapSphere (explosionPos1, radius);
for(var n = 0; n < returnarray.length; n++) {
if(returnarray[n].gameObject.name == "Warehouse Container Red"){
returnarray[n].rigidbody.useGravity = false;
returnarray[n].transform.RotateAround (transform.position, Vector3.up, rotatetime * Time.deltaTime);
returnarray[n].transform.position = Vector3.Lerp(returnarray[n].transform.position, transform.position, speedtime);
}
}
Ok well to limit to just the 5 returns I would have the FOR statement like this:
for(var n = 0; n < 5; n++) { //Limits it to the first 5 indexes regardless of what the returns are
Remember also, the string value of "Warehouse Container Red" is case sensative. If you are trying to find 5 Warehouse Container Red's out of all the overlap sphere returns that's a bit different.
To sift through the returns and find only certain returns using Overlap sphere, you might want the if execution a bit different. I've updated the answer to reflect this.
Your answer
Follow this Question
Related Questions
get nearest instance of game object 1 Answer
Player hanging on objects. 0 Answers
Object carry in game 1 Answer
Deactivate/activate objects depending on player position 2 Answers