1
\$\begingroup\$

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)) {
            AddEnemiesToList(enemy.transform);
        }
    }
}

public void AddEnemiesToList (Transform enemy) {
    enemies.Add(enemy);
}
}
\$\endgroup\$
1
\$\begingroup\$

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) {
        enemies.Add(enemy.transform);
    }
}

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");
  }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Wow. So simple, can't believe I didn't think of that.. Thank you! \$\endgroup\$ – Adariel Lzinski Jun 6 '15 at 3:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.