- Home /
Finding nearest object with a certain tag without for loops.
Hi, so I am trying to optimize my for loop heavy A* code and am wondering if I can find the nearest object with a certain tag without using for loops. I currently have that it do a for loop of all the tagged objects and pick the nearest one. Thanks!
So this is an Open List find the lowest F score? Or is this a neighbour search? I can't quite work out where that is going to be in a A* implementation. Seeing some script would be good.
You could for instance possible map these on to a 2D grid and then search out from the start point in that grid, if you complete one grid "square" of distance (and process the items in it) then if it has any contents, one of them must be the closest object.
This is to find which node the player and zombie is closest to in order to use them as the starting and ending node. Do you understand what I mean?
Answer by Jessy · May 02, 2013 at 04:12 PM
I bet that searching by tag is a bottleneck and I'd avoid it. A HashSet could be a better match; add and remove from it as necessary. You can't avoid the loop under the hood, but you don't have clutter up your code by actually typing it:
HashSet<Transform> stuffThatWasTagged;
Vector3 position = transform.position;
Transform closest = stuffThatWasTagged.Min( t => (t.position - position).sqrMagnitude );
Your answer
Follow this Question
Related Questions
How do I reset a for loop variable??? 3 Answers
x=x Assignment made to same variable 3 Answers
Having Trouble with this For Loop 1 Answer
JS Loop question 2 Answers
For statement stops function? 1 Answer