# Update total enemy counter after single enemy is defeated?

So I have a list that counts how many enemies are in the area. But when I kill an enemy, the list shows that that element in that array is missing, and doesn't reduce the enemy counter. How can I get it to reflect when an enemy is defeated?

Code:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EnemyCount : MonoBehaviour {
public List<Transform> enemies;

void Start () {
enemies = new List<Transform>();
}

void Update () {
FindAllEnemies();
}

public void FindAllEnemies () {
GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");

foreach (GameObject enemy in go) {
//Checks for duplicates
if (!enemies.Contains(enemy.transform)) {
}
}
}

public void AddEnemiesToList (Transform enemy) {
}
}


If I understand correctly your question, one way to achieve it would be to clear the list each frame to make sure you list is always up to date. Please note that I do not know exactly the syntax to clear a list, but your function would look like this:

public void FindAllEnemies () {
GameObject[] go = GameObject.FindGameObjectsWithTag("Enemy");

enemies.Clear(); // Probably not the right function name...
foreach (GameObject enemy in go) {
}
}


Edit

In fact, you could even do something like this if it suits your needs:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class EnemyCount : MonoBehaviour {

public List<GameObject> enemies;

void Start () {
enemies = new List<GameObject>();
}

void Update () {
FindAllEnemies();
}

public void FindAllEnemies () {
enemies = GameObject.FindGameObjectsWithTag("Enemy");
}
}

• Wow. So simple, can't believe I didn't think of that.. Thank you! – Adariel Lzinski Jun 6 '15 at 3:42