- Home /
FindWithTag in certain range
I'm trying to add nodes to an Array but the nodes need to be within a certain range. I tried this to see if I could achieve this:
Collider[] colls = Physics.OverlapSphere(AI.position, distance);
foreach (Collider col in colls){
nodes = GameObject.FindGameObjectsWithTag("Node");
}
I knew it wouldn't work, so what I tried to do was individually add each node inside the foreach:
Collider[] colls = Physics.OverlapSphere(AI.position, distance);
foreach (Collider col in colls){
nodes.Add(col);
}
And I made 'nodes' an ArrayList. Unfortunately though, it kept adding the same nodes over and over again until I had hundreds of the same nodes inside my ArrayList. How should I FindGameObjectsWithTag inside a certain range?
I am wondering what comes before and after this code? Could it be that you are running this each frame? Cause if you do, you will add the same colliders each frame until the overlap stops...
Yeah it's in update because it needs to be dynamically searching for new nodes every frame.
Answer by save · Apr 08, 2012 at 09:03 AM
Simply change the tag after it's made it into the list. You should consider using a collider set to trigger instead if this has to run every frame.
Well the other problem is that it needs to be within a certain range. Your answer should work to keep it from re-adding itself, but would it still keep the nodes within a certain range?
Wait a second...this does solve the problem! Thanks. And to find the nodes in the range, the script ended up like this:
Collider[] colls = Physics.OverlapSphere(AI.position, distance);
foreach (Collider col in colls){
if(col.tag == "Node"){
nodes.Add(col);
col.tag = "NodeU";
}
}
Thanks a lot! Not sure why I didn't think of this before....
One of the things I need though that I forgot to ask is if the nodes are no longer inside the OverlapSphere, that they are removed from the ArrayList 'nodes' and that their tag is no longer 'NodeU'. You would this it'd be something simple like:
foreach (Collider col !in colls){
But it doesn't work that way. Is there a way to do this?
Oh never$$anonymous$$d, figured that out too. Thanks for your help.
Answer by darkcookie · Apr 08, 2012 at 09:07 AM
http://unity3d.com/support/documentation/ScriptReference/GameObject.FindGameObjectsWithTag.html
theres an example code there ...hope it helps
I have no idea why this happens, but the code gives up a 'use of unassigned local variable 'closest'' error when I copy and paste it....so Unity should get that checked out, because the error is in the middle of the script, so I have no idea why it's giving up an error.
And that also solves my problem for the nearest node, but it doesn't solve my problem for nodes within a range, and I'm not sure how to change it to do that. Thanks though. Oh, and I fixed the error.