I have a question. Im trying to create a spawner with max limit of 4 spawns. But if a spawn is destroyed I want to start the spawning again up until the number reaches max again. Below I have the code but my spawner just keeps spawning objects over the limit. Can somebody help me?
public class EnemySpawner : MonoBehaviour
{
[SerializeField] GameObject enemyPrefab;
[SerializeField] private float spawnRate = 4f;
[SerializeField] int spawns;
private int xPos;
private int zPos;
private int spawnsLimit = 4;
private void Start()
{
spawns = GameObject.FindGameObjectsWithTag("Enemy").Length;
if (spawns < spawnsLimit)
{
StartCoroutine(EnemySpawn());
}
else if (spawns > spawnsLimit)
{
StopCoroutine(EnemySpawn());
}
}
IEnumerator EnemySpawn()
{
xPos = Random.Range(-20, 20);
zPos = Random.Range(-20, 20);
Instantiate(enemyPrefab, new Vector3(xPos, 1, zPos), Quaternion.identity);
yield return new WaitForSeconds(spawnRate);
StartCoroutine(EnemySpawn());
}