focusing on a unit during unit detection in an RTS

Hey guys,
I have an enemy unit which detects a player unit within 10 distance and then goes to its position. The problem is, when there are other units within 10 units distance, the enemy unit switches back and forth between the units. Is there a way I can make my enemy unit focus on the position of a single controlled player unit instead of all of them? I want to eventuall make it so the enemy chooses the nearest unit. Thanks,
Code is posted here:

IEnumerator distanceBoolToggle(){ //included in the coroutine to save memory

		while (numeratorBool==false) {

				for (int i=0; i<UnitsList.Count; i++) { //this iterates through my list of player-unit objects
										float distance = Vector3.Distance (transform.position, UnitsList *.transform.position);*
  •  								//this calculates the distance from one player-unit to enemy unit*
  •  								if (distance <= 10) { //if the distance is less than 10 between player unit and enemy unit*

_ GameObject playerObject = UnitsList ; //creates an object for that specific player unit_

* AstarAI playerObjectDetection = playerObject.GetComponent (); //gets astarai code for that unit*

* targetPosition = playerObjectDetection.transform.position; //sets the enemy position to the pos of the player unit*

* float distanceToTargetPos = Vector3.Distance (transform.position, targetPosition); //finds distance between the two units*

* if (distanceToTargetPos > 3) {*

* seeker.StartPath (transform.position, targetPosition, OnPathComplete); //if distance is more than 3 than travel towards its destination*

* }*

* }else{*
* }*

* }*

* yield return new WaitForSeconds (1f);*
* }*
* } *

I would suggest only going through the list if there is no current target.

Something like this (meta code only)

  1. Define a private GameObject currentTarget
  2. If currentTarget = null or currentTarget distance > ten
  3. Run your code to find and assign a new currentTarget

An alternative is to use a trigger and create a private list on the enemy that grabs each player unit as it comes into range and deletes it as it leave range. This could make your script much cheaper to run as it only has to run through the units that are close, rather than every player unit on the map.

I’d also suggest using Vector3.sqrMagnitude instead of Vector3.Distance. Much faster for straight comparisons as there is no square root involved.