2d targetting system bug c#

Hi all I hope someone can give me some advice. I have a 2d targetting system where the targets are coming from left to right. The closest target is picked up and then attacked when it comes within a certain range. All the targets although there are four different types all have the same “AllyTag”. When I instantiate more than one target the the most recently instantiated target is attacked and not the closest. Cn anyone see where I am going wrong?

void TargetSearch(){
		enemies = GameObject.FindGameObjectsWithTag("AllyTag");
		transform.LookAt(target);
		
		
		if(enemies.Length > 0 ){
			closestEnemy = enemies[0];
			float dist = Vector3.Distance(transform.position,enemies[0].transform.position);
			int i ;
			
			for(i = 0 ; i<enemies.Length; i++){
				float tempDist = Vector3.Distance(transform.position, enemies*.transform.position);*
  •  	    if(tempDist < dist){*
    

_ closestEnemy = enemies*;_
_
}_
_
}_
_
//do something with the closest enemy*_
* c = closestEnemy.transform.position.x;*
* xa= transform.position.x;*
* if(c>=xa-distance && sec == false ){//sec is for the gap in attacks*
* //stop and shoot*
* currentSpeed = 0;*
_ if(currentSpeed == 0){StalkerAnim.PlayAnim(1);/audio.PlayOneShot(Uzi);/}else{StalkerAnim.PlayAnim(0);} _
sec = true;
* StartCoroutine(Wait());*
* //if(closestEnemy==null && currentSpeed == 0){Wait2();}*
}
* }*

* }*

You aren’t updating your “dist” variable with the closer enemy’s distance when you find one, this means you are taking not the closest enemy in your list, but rather the last one that was closer than the first enemy. Try setting dist = tempDist right after setting the new closetEnemy