Count not decreasing after object destruction.

Hey guys so in my enemy spawner script I set the max number of enemies to 10 but it just spawns 10 enemies and then stops. I noticed that in the inspector the enemy count did not decrease as enemies were destroyed so that’s probably why. How do I get the count to decrease?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy_Spawn_script : MonoBehaviour
{
    public GameObject theEnemy;
    public float xpos;
    public float ypos;
    public int enemyCount;
    void Start()
    {
        StartCoroutine(EnemyDrop());
    }
    IEnumerator EnemyDrop()
        {
            while (enemyCount< 10)
            {
                xpos = Random.Range(1, 5);
                ypos = Random.Range(4, 8);
                Instantiate(theEnemy, new Vector3(xpos, ypos, 0), Quaternion.identity);
                yield return new WaitForSeconds(1);
    enemyCount += 1;
            }
        }
 
}

Hey,

So two things…

  1. If your enemy count reaches 10, your coroutine will end and never start again. This is likely the issue.

  2. You need to reduce the enemy count when they die, which I assume you’re already doing.

To solve the first issue, you can put all of your coroutine logic in a perpetual while loop like this:

    IEnumerator EnemyDrop()
    {
        while (true) // This makes sure your coroutine never stops unless you stop it manually.
        {
            while (enemyCount < 10)
            {
                xpos = Random.Range(1, 5);
                ypos = Random.Range(4, 8);
                Instantiate(theEnemy, new Vector3(xpos, ypos, 0), Quaternion.identity);
                yield return new WaitForSeconds(1);
                enemyCount += 1;
            }
            yield return null; // You need this to avoid an infinite loop.
        }
    }

Let me know is that solves it, good luck!

Also, please note that you should post scripting issues on the Scripting forum. We try to keep this forum for 2D related posts and not posts for any issue whilst making a 2D game.