using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemySpawner : MonoBehaviour {
public GameObject enemy;
public float spawnTime = 10f;
public Transform[] spawnPoints;
void Start()
{
InvokeRepeating("Spawn", spawnTime, spawnTime);
}
void Spawn()
{
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
Instantiate(enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}
}
but now i want it only to spawn enemys if there is less then three…
ply help
If you want to have only 3 spawned enemy, you can track exists enemies adding them on spawn to collection, remove on death, and put flag before spawning which’ll check if there is 3 enemies in collection or not.
void Spawn()
{
// if there are more than 3 enemies, return - so, prevent execution of spawn code
if(enemy > 3)
{
return;
}
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
Instantiate(enemy, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation);
}
OP: On one of the enemy scripts, keep a variable for the Enemy Spawner. When you instantiate your game object, assign the reference of the spawner to the newly created enemy. When it dies, call a method (on Enemy Spawner) that will subtract 1 from the enemy count.
So, once the enemy count is at 3, the coroutine should continue to yield the wait time. Once the count drops below that, it should spawn them (again).
Also, as mentioned, please be more descriptive in what’s wrong when something is not working as you want it to. We’re not mind readers
Then you would suggest what to keep track of the number of alive enemies? It would be a good follow up for your post, if you included something you thought was a good alternative.
Well at the end of the day, it’s up to OP to determine how he wants to do this. He hasn’t even replied to my code (I’ve edited it after @methos5k pointed out the coroutine issue I overlooked, thanks) yet. Personally, what I’d do is when an enemy dies, a script on the enemy can simply access the enemyCount in EnemySpawner class. For OP:
public EnemySpawner ES;
void OnEnemyDeath()
{
ES.enemyCount--;
}