I’m running a targeting script which attempts to find the number of enemies on the map and place them in an array which can then later be sorted. While Debug.Log(EnemyList.Length) returns the appropriate number of enemies (usually around 5) it is looped over 40 times in the console. Any ideas why this might be happening?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TowerBehavior : MonoBehaviour {
public long health;
public long range;
public List <GameObject> enemies;
void Start () {
enemies = new List<GameObject> ();
StartCoroutine (AquireTarget ());
}
void Update () {
if (health <= 0) {
transform.position = new Vector3(0,-100,0);
}
}
IEnumerator AquireTarget() {
while (true) {
yield return new WaitForSeconds (5);
AddEnemiesToList ();
}
}
private void AddEnemiesToList () {
GameObject[] EnemyList = GameObject.FindGameObjectsWithTag ("Enemy");
foreach (GameObject x in EnemyList) {
AddTarget(x);
Debug.Log (EnemyList.Length);
}
}
private void AddTarget(GameObject t) {
enemies.Add (t);
}
void OnTriggerEnter(Collider col) {
if (col.gameObject.tag == "Enemy") {
health = health -10;
}
}
}