suleman ali
suleman ali

Reputation: 37

how to keep count on how many left of the instantiated clones i.e enemy

I'm using the following script to instantiate the enemy clones but I'm unable to keep track of how many have been instantiated or are left in the scene.

public GameObject playerhealth;
public GameObject enemy;
public float spawnTime= 3f;
public Transform spawnPoint;

public float dis;
public static GameObject obj;

void Start(){
    Invoke ("Spawn", spawnTime);
}

void Spawn(){

    if (dis < 100) {

        obj =   Instantiate (enemy, spawnPoint.position, spawnPoint.rotation);

        obj.name = "Abc";

    }
}       

Upvotes: 2

Views: 393

Answers (3)

Alex Myers
Alex Myers

Reputation: 7215

You can keep track of your enemies by adding/removing them from a List as you spawn and destroy them.

List<GameObject> enemies = new List<GameObject>();

obj = Instantiate (enemy, spawnPoint.position, spawnPoint.rotation);
enemies.Add(obj);

When you need to remove it, simply call enemies.Remove() and pass a reference to the enemy GameObject being removed.

You can also use GameObject.FindGameObjectsWithTag to find all enemies in your scene after the fact if they all have the same tag.

GameObject[] enemies;

enemies = GameObject.FindGameObjectsWithTag("Enemy");

Upvotes: 2

victor dabija
victor dabija

Reputation: 505

I would sugest you to use a component attached, so you can use it for all prefabs, and adapt it in every project, to retrieve your counter just use EnemyCounter.enemiesAlive. You have to attach this script to your enemy prefab/s and it will work if you want just the counter. if you also want to keep track of your enemy prefabs use a List<> as suggested in other answers.

public class EnemyCounter: MonoBehaviour
  {
    public static int enemiesAlive=0;

    void OnEnable()
      {
        enemiesAlive++;
      }

    void OnDisable()
      {
        enemiesAlive--;
      }

}

Upvotes: 2

paul p
paul p

Reputation: 450

    List <GameObject> _list; 
public GameObject obj;

 void Spawn()
{

if (dis < 100) {

    obj =   Instantiate (enemy, spawnPoint.position, spawnPoint.rotation);

    obj.name = "Abc";
    _list.Add(obj);

}

   void Update()

{
 //TO get count
  _list.Count;
 }

Upvotes: 1

Related Questions