Search Unity

Counting GameObjects that are active..

Discussion in 'Scripting' started by suspensemusic, Jan 4, 2014.

  1. suspensemusic

    suspensemusic

    Joined:
    Dec 4, 2013
    Posts:
    41
    I have figured out how to count the enemies that have been created. But I can't figure out how to keep an updated number. Once I hit 10 it stops working. I need to know how to reference this function and subtract 1 from the length every time an object dies...

    I think I have an idea of how to do this but I haven't figured it out yet. (This would need to be called from a different script).

    Code (csharp):
    1.     void SpawnEnemy () {
    2.         enemyCount = GameObject.FindGameObjectsWithTag ("enemy").Length;
    3.         Debug.Log (enemyCount);
    4.             if (enemyCount <= 10){
    5.                 Vector3 spawnPosition = transform.position + ((Vector3)Random.insideUnitCircle).normalized*spawnRadius;
    6.                 Instantiate(enemyType,spawnPosition,enemyType.transform.rotation);
    7.                 Invoke("SpawnEnemy", spawnDelay);
    8.             }
    9.         }
     
  2. softwizz

    softwizz

    Joined:
    Mar 12, 2011
    Posts:
    793
    what stops working?

    When it gets to 10 enemies there will be no more spawned.

    When an enemy is removed cant you use
    Code (csharp):
    1. enemyCount.length--
     
    Last edited: Jan 4, 2014
  3. TheShane

    TheShane

    Joined:
    May 26, 2013
    Posts:
    136
    What doesn't work? You should always find all objects tagged as "enemy", and if you properly destroy the enemy (or change its tag) when it dies, then the count will be "updated" automatically. "Updated" in the sense that Unity will go through your scene and count them every time you call FindGameObejctsWithTag() so the returned count should always be current.
     
  4. suspensemusic

    suspensemusic

    Joined:
    Dec 4, 2013
    Posts:
    41
    I thought it would update but it doesn't... It just stops at 10 even though I am destroying the object
     
  5. softwizz

    softwizz

    Joined:
    Mar 12, 2011
    Posts:
    793
    as a test can you reset the enemyCount before enemyCount = GameObject.FindGameObjectsWithTag ("enemy").Length; at the start of the method
     
  6. suspensemusic

    suspensemusic

    Joined:
    Dec 4, 2013
    Posts:
    41
    I have actually just changed this entire code.. Instead of counting objects with tags I am just going to increase an int inside a ManagerClass each time I spawn an enemy. And then subtract it as I destroy them.

    Honestly that is probably a better design decision anyway.
     
  7. softwizz

    softwizz

    Joined:
    Mar 12, 2011
    Posts:
    793
    Good plan.