Player gameObjects automatically check if enemies are in range and attack them.
To reduce calculations, gameObjects find the closest enemy every 5 seconds. If the closest enemy is in range, Attack() is activated. If not, then they find the closest enemy after another 5 seconds. Somehow, results of the search alternate between the actual closest enemy and the next closest one. So, if the closest enemy is in range, Attack() activates for 5 seconds and then deactivates for the next 5 if the next closest enemy is out of range. What am I doing wrong?
void Update()
{
if (inRange == true)
Attack();
attackTimer -= Time.deltaTime;
if (attackTimer <= 0)
{
currentTarget = findClosestTarget();
if (Vector3.Distance(this.transform.position, target[currentTarget].transform.position) < (maximumRange + 5))
{
inRange = true;
}
else
{
inRange = false;
}
attackTimer = 5;
}
}
}
}
int findClosestTarget()
{
if (target.Count == 0) return -1;
for (int i = 1; i < target.Count; i++)
{
if (target *== null)*
{
target.Clear();
PopulateTargetList();
}
}
int closest = 0;
float lastDist = Vector3.Distance(this.transform.position, target[0].transform.position);
for (int i = 1; i < target.Count; i++)
{
float thisDist = Vector3.Distance(this.transform.position, target*.transform.position);*
if (lastDist > thisDist && i != currentTarget)
{
closest = i;
lastDist = thisDist;
}
}
return closest;
}
public void PopulateTargetList()
{
GameObject[] enemyUnitsPresent = GameObject.FindGameObjectsWithTag(targetTag);
for (int i = 0; i < enemyUnitsPresent.Length; i++)
{
if (enemyUnitsPresent*.GetComponent().aircraft == false)*
target.Add(enemyUnitsPresent*);*
}
}