- Home /
Question by
Vannerss · Apr 01 at 02:38 AM ·
instantiateloopingenemy spawnspawning-enemies
How to spawn objects but set a cap of how many can be alive at the same time?
I'm currently making a small co-op round base zombie shooter for educational purposes and I'm trying to spawn a total amount of Zombies per round but limit the amount of zombies that can be alive at the same time so that when you get to later round the game doesn't crash for having too many zombies.
i.e at round 20 the total amount of zombies spawning is 100 but only 25 zombies can be alive at the same time. So i would like that when i reach the cap of zombies, the rest of the 75 zombies don't spawn until the next one dies.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyManager : MonoBehaviour
{
//-------------singleton-----------------
public static EnemyManager instance;
private GameManager gameManager;
public GameObject enemyPrefab;
public Transform[] spawnPoints;
public delegate void AllZombiesKilled();
public static event AllZombiesKilled onAllZombiesKilled;
const int maxZombieSpawn = 25;
const float difficultyMultiplier = 0.15f;
int amountToSpawn;
int maxAmountofZ;
private void OnEnable()
{
GameManager.onRoundStarted += SpawnZombies;
}
private void OnDisable()
{
GameManager.onRoundStarted -= SpawnZombies;
}
private void Awake()
{
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
}
void Start()
{
gameManager = GameManager.instance;
}
void SpawnNewEnemy(int amount)
{
for(int i = amount; i > 0; i--)
{
int holder = i;
if (GameObject.FindGameObjectsWithTag("Enemy").Length < maxZombieSpawn)
{
Instantiate(enemyPrefab, spawnPoints[0].transform.position, Quaternion.identity);
}
else
{
i = holder + 1;
}
}
}
void SpawnZombies()
{
switch (gameManager.currentRound)
{
case 1:
Debug.Log("case 1");
amountToSpawn = Mathf.RoundToInt(maxAmountofZ * 0.2f);
SpawnNewEnemy(amountToSpawn);
break;
case 2:
amountToSpawn = Mathf.RoundToInt(maxAmountofZ * 0.4f);
SpawnNewEnemy(amountToSpawn);
break;
case 3:
amountToSpawn = Mathf.RoundToInt(maxAmountofZ * 0.6f);
SpawnNewEnemy(amountToSpawn);
break;
case 4:
amountToSpawn = Mathf.RoundToInt(maxAmountofZ * 0.8f);
SpawnNewEnemy(amountToSpawn);
break;
case int n when (n >= 5 && n <= 9):
amountToSpawn = maxAmountofZ;
SpawnNewEnemy(amountToSpawn);
break;
case int n when (n >= 10):
amountToSpawn = Mathf.RoundToInt((gameManager.gameRound * difficultyMultiplier) * maxAmountofZ);
SpawnNewEnemy(amountToSpawn);
break;
default:
break;
}
}
}
my solution was to ad the if-statement inside the for-loop but when the I try spawning a number of enemies higher than the maxAmount my whole unity freezes without even saying it crashed. A complete stop.
Comment