I am currently building a wave base game in Unity, but I am currently stuck. My goal is to have 3 enemies spawning at different rates independently. I have one big class that manages the Waves and in which I store data like Enemy1Count (How many Enemy1 spawn), Enemy1Rate (At which rate they spawn). I want the first enemy to spawn every 2 seconds, the second enemy to spawn every 3 seconds and the third enemy to spawn every 5 seconds, but I can't make that happen without the timers affecting each other. Do you have any idea how I could solve that? (I would like to manage all the data for the 3 enemies within one class)
CodePudding user response:
This seems like a problem where you can definitely use Unity Coroutines, you should be able to run a coroutine per enemy so it will spawn a wave after X amount of time.
Something like this should work for your logic
Coroutine c1, c2,c3;
bool keepSpawningEnemies = true;
Start(){
c1= StartCoroutine(SpawnWave(enemy1, 3.0f));
c2= StartCoroutine(SpawnWave(enemy2, 10.0f));
c3= StartCoroutine(SpawnWave(enmey3, 5.0f));
}
IEnumerator SpawnWave(Enemy enemy, float timeBetweenWaves)
{
while(keepSpawningEnemies ) {
SpawnWaveLogic(enemy);
yield return new WaitForSeconds(timeBetweenWaves);
}
}
Update() {
// logic to check if we need to keep spawning
// At some point you would run
keepSpawningEnemies = false;
}
CodePudding user response:
I think the simplest way is to create a component that is responsible for handling just one wave, then add three instances of that component to the scene.
public class Spawner : MonoBehaviour
{
[SerializeField] private Object prefab;
[SerializeField] private float spawnInterval;
private WaitForSeconds waitForNextSpawn;
private void Awake() => waitForNextSpawn = new WaitForSeconds(spawnInterval);
private void OnEnable() => StartCoroutine(SpawnLoop());
private void OnDisable() => StopCoroutine(SpawnLoop());
private IEnumerator SpawnLoop()
{
while(enabled)
{
yield return waitForNextSpawn;
Instantiate(prefab);
}
}
}