finding game objects within a certain distance

is there a way to find game objects within a certain distance? right now i have the following code:

var trees = new Array(3);
var bill = new Array();
var lowPoly = new Array();
var highPoly = new Array();

function Awake (){
bill = GameObject.FindGameObjectsWithTag(“Bill”);
lowPoly = GameObject.FindGameObjectsWithTag(“LowPoly”);
highPoly = GameObject.FindGameObjectsWithTag(“HighPoly”);
trees[0] = bill;
trees[1] = lowPoly;
trees[2] = highPoly;
}

function Update(){
for(var i = 0; i < 3; i++){
for(var j = 0; j < trees*.length; j++){*
_ var tree = trees*[j];_
_
var diff = (tree.transform.position) - transform.position;_
_
var distance = diff.sqrMagnitude;_
_
var treePos = tree.transform.position;_
_
print(treePos);_
_
var newTree;*_

* if(distance > 320 (tree.transform.tag != “Bill”)){*
* Destroy(tree);*
* newTree = instantiateBill(tree, treePos);*
* bill.Add(newTree);*
_ trees*.RemoveAt(j);
}
else if((distance > 70 distance < 300) (tree.transform.tag != “LowPoly”)){
Destroy(tree);
newTree = instantiateLowPoly(tree, treePos);
lowPoly.Add(newTree);
trees.RemoveAt(j);
}
else if(distance < 50 (tree.transform.tag != “HighPoly”)){
Destroy(tree);
newTree = instantiateHighPoly(tree, treePos);
highPoly.Add(newTree);
trees.RemoveAt(j);
}
}
}
}*

the problem with this code is that every update, it has to go through ALL the trees on the terrain (either tagged bill, lowPoly, or highPoly). needless to say, this is way too costly. any ideas?_

Have you considered using Physics.OverlapSphere() ?

Description:
Returns an array with all colliders touching or inside the sphere.

Yes, that is excessive, especially since your data set could contain 40’000 trees :slight_smile:

For something like this, I’d write a simple quadtree (a tree data structure, not a plant :stuck_out_tongue: ) to encpsulate all the trees, this way, you would dramatically cut down the amount of tests needed. Have a look into this way of scene partitioning, it should be doable as a script as well.

Why not use a sphere collider in conjunction with the “OnTriggerEnter” and “OnTriggerExit” functions. Just keep a sorted list of ones inside the collider (I usually sort by InstanceID).

I would also recommend using the collider/trigger way. I’ve done it that way once, and it’s fairly straightforward. It has the added advantage that you can decide where to put the action it should trigger - on the various objects or the controller.