# Finding a the closest distance between a Ai and multipel enemys

Hello i am trying to make a A.I. that can find all of the enemys on the screen and target the closest one to it.I don’t know how to do this can you help me on that please?
So far i have made it so that it finds any enemy with a tag and goes for it,but of course this can cause the A.I. to go for a random enemy and that is bad.
Here is the code:

``````void Ai(){

GameObject Target;
Vector2 TargetPos;

Target = GameObject.FindGameObjectWithTag ("Bad");
TargetPos = Target.transform.position;
transform.position = Vector2.MoveTowards (transform.position, TargetPos, Speed * Time.deltaTime);

}
``````

You can use ` GameObject[] Target = GameObject.FindGameObjectsWithTag ("Bad");`. That returns every Gameobject with the give tag.

public GameObject Enemies;
public GameObject Target;
public Vector2 TargetPos;
public float Speed = 5;

``````    void Ai()

{

Enemies = GameObject.FindGameObjectsWithTag("Bad"); // Find all enemies

if(Enemies.Length > 0)
{
float distance = 10000;
for(int i = 0; i < Enemies.Length; i++)
{
if(Vector2.Distance(transform.position, Enemies*.transform.position) < distance)*
``````

{
//If distance between you and this enemie is less than distance, set this enemy to target and the distance to distance to check
Target = Enemies*;*
distance = Vector2.Distance(transform.position, Enemies*.transform.position);*
TargetPos = Target.transform.position;
}
}
}

transform.position = Vector2.MoveTowards(transform.position, TargetPos, Speed * Time.deltaTime); // the most closer enemy

}