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!

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 );