I have this script attached to my friendlyUnits, one timeToAttack is true they move towards to same enemyUnit and believe me one enemyUnit is closer than the other one to my second friendlyunit.
GameObject closest;
PlayerControls controls;
float speed = 7;
bool foundControls;
void Start()
{
foundControls = false;
FindClosestEnemy();
controls = GameObject.FindGameObjectWithTag("GamePlay").GetComponent<PlayerControls>();
}
void Update()
{
if (controls.timeToAttack == true)
{
float step = speed * Time.deltaTime;
gameObject.transform.position = Vector3.MoveTowards(gameObject.transform.position, closest.transform.position, step);
}
}
#region findClosest
GameObject FindClosestEnemy()
{
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Player");
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos)
{
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
if(closest!=null)
Debug.Log(closest.name);
return closest;
}
#endregion