limit number of gameobjects instantiated

Hello all!!

Sorry for my another stupid question…

Also following the Survival Shooter Tutorial, I’m using the enemyManager script.

It spawns clones (from prefab) as I want. But I do want to limit their number (ressources issues)

How can I do that?

Here’s the full code :



using UnityEngine;

public class EnemyManager : MonoBehaviour
{
public PlayerHealth playerHealth;
public GameObject enemy;
public float spawnTime = 3f;
public Transform spawnPoints;

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

void Spawn ()
{
	
	if(playerHealth.currentHealth <= 0f)
	{
		
		return;
	}

	int spawnPointIndex = Random.Range (0, spawnPoints.Length);

	Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}

}

int maxEnemy = 50;
int enemyCount = 0;

void Spawn()
{
	if(enemyCount >= maxEnemy) return;
	// Instantiate
	enemyCount++;
}

That is quite an easy approach. If you are going to kill the enemies, you should decrease the enemyCount, and the method will create a new one.

However, if you are not going to do much with them, you should probably cancel the invoke by calling

CancelInvoke("Spawn");

and restart the invoke when you need it. This thing is for performance-efficiency.