Find nearest GameObject with specific tag

Hi
I want my ally to find nearest enemy, but I don’t understand how it works. Everywhere are only complete scripts. I want my script to set nearest GO with tag “Enemy” as a script’s public GameObject “Enemy”.
I’ve tried second example from here: Unity - Scripting API: GameObject.FindGameObjectsWithTag and I changed closest to Enemy, but it doesn’t work. Can someone explain me what is wrong?

Hi @b4gieta

You could use overlap sphere Unity - Scripting API: Physics.OverlapSphere

Your npc helper probably has maximum view range, so use that as sphere radius to get all colliders on area around him.

Then go through those colliders and see if any collider GameObject has enemy tag, or use LayerMask to avoid using tags altogether.

Then check each enemy distance to your ally and pick the closest one.

Well, I forgot to tell that game is 2D, so I need to find nearest enemy only in X axis.