Most efficient way of detecting closest objects around?

I’m considering how to detect the closest object around my hero.
This is gonna be called for every frame so I really need the most efficient way.

Should I do a For loop of my array of objects and calculate the distance of each object to my hero and choose the smallest value?

Or should I use other means such as raycasts?

I’m targeting mobile so every bits of CPU saving helps.

Physics engine inside unity keeps colliders in some structure that makes if fast to query objects in an area (99% sure it’s an octree). So when you are using Physics.OverlapSphere, it should be optimized and fast.
This will only work with colliders though, not with any GO / Transform (since the octree is part of physics engine) and if you plan to move them around, you’d better have a kinematic rigidbody there as well.

If you need / want, you can implement your own octree and fill it with your objects. This can be handy if you want to have multiple parallel “worlds” populated with objects where you can search, or you simply don’t want to use colliders and physics and waste some unity layers for filtering them out.

If you’re looking for pure efficiency, you might want to consider using a trigger area collider sphere around your character.

As a script on that, you would use OnTriggerEnter() to compile a running List<> of objects as your character gets near them and then OnTriggerExit() to clear them out of the list.

Then, you’ll only need to check whichever objects are contained within a close range of you to determine which is closest after that.

If you have extremely few objects in the scene or they’re all generally going to be very, very far away (and you still want to know which is closest), then you might consider alternative methods instead.

Edit: Fixed formatting for “List<>”