Hello everyone,
I was doing the Brackey’s tutorial on wave spawner. It taught me how to have multiple waves & spawners but the things is, each wave can only spawn ONE type of enemy. I want to have an array of enemies that I can insert into each wave so that each wave can have multiple types of enemies spawning. Here’s the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class spawnerScript : MonoBehaviour
{
[System.Serializable]
public class Wave
{
public string name;
public Transform enemy;
public int count;
public float rate;
}
public enum SpawnState { SPAWNING, WAITING, COUNTING};
public SpawnState state = SpawnState.COUNTING;
public Wave[] waves;
private int nextWave = 0;
public float timeBetweenWaves = 5f;
public float waveCountdown;
private float searchCd = 1f;
public Transform[] spawnPoints;
void Start()
{
waveCountdown = timeBetweenWaves;
if (spawnPoints.Length == 0)
{
Debug.LogError("no spawn points");
}
}
void Update()
{
if (state == SpawnState.WAITING)
{
if (!EnemyIsAlive())
{
waveCompleted();
return;
}
else
{
return;
}
}
if (waveCountdown <= 0)
{
if(state != SpawnState.SPAWNING)
{
StartCoroutine(SpawnWave(waves[nextWave]));
}
}
else
{
waveCountdown -= Time.deltaTime;
}
}
void waveCompleted()
{
Debug.Log("Wave Completed!!");
state = SpawnState.COUNTING;
waveCountdown = timeBetweenWaves;
if (nextWave + 1 > waves.Length - 1)
{
nextWave = 0;
Debug.Log("You won. Looping. Good luck.");
}
else
{
nextWave++;
}
}
bool EnemyIsAlive()
{
searchCd -= Time.deltaTime;
if (searchCd <= 0f)
{
searchCd = 1f;
if (GameObject.FindGameObjectWithTag("Enemy") == null)
{
return false;
}
}
return true;
}
IEnumerator SpawnWave(Wave wave)
{
Debug.Log("Spawning wave: "+ wave.name);
state = SpawnState.SPAWNING;
//SPAWN
for (int i = 0; i <wave.count; i++)
{
SpawnEnemy(wave.enemy);
yield return new WaitForSeconds(1f/wave.rate);
}
state = SpawnState.WAITING;
yield break;
}
void SpawnEnemy(Transform _enemy)
{ Debug.Log("Spawning "+ _enemy.name);
Transform spawnP = spawnPoints[Random.Range(0, spawnPoints.Length)];
Instantiate(_enemy, spawnP.position, Quaternion.identity);
}
}
I’ve never been too great at arrays, and I’ve been trying to get my head around this for hours. Thanks in advance.