I managed to spawn enemies but they keep spawning. How can I set a limit to avoid from spawning unceasingly?
I've tried to add spawnLimit and spawnCounter but couldn't manage it to work.
var playerHealth = 100; // Reference to the player's heatlh.
var enemy : GameObject; // The enemy prefab to be spawned.
var spawnTime : float = 3f; // How long between each spawn.
var spawnPoints : Transform[]; // An array of the spawn points this enemy can spawn from.
function Start ()
{
// Call the Spawn function after a delay of the spawnTime and then continue to call after the same amount of time.
InvokeRepeating ("Spawn", spawnTime, spawnTime);
}
function Spawn ()
{
// If the player has no health left...
if(playerHealth <= 0f)
{
// ... exit the function.
return;
}
// Find a random index between zero and one less than the number of spawn points.
var spawnPointIndex : int = Random.Range (0, spawnPoints.Length);
// Create an instance of the enemy prefab at the randomly selected spawn point's position and rotation.
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}
You can use this kind of counter:
int maxEnemies = 100;
int enemiyCounter = 0;
and in Spawn()
add:
if(enemiyCounter < maxEnemies){
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
enemyCounter++;
}
instead of
Instantiate (enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);