- Home /
Wave Spawning not working
Hi, trying to use an ienumerator for a wave spawning script, i could get it to spawn enemies every few minutes but i'm trying to use waves but it just crashes when it starts
public class SpawnController : MonoBehaviour
{
public GameObject Enemy = null;
public GameObject[] enemys;
public float spawnWait;
public float startWait;
public float waveWait;
public float waveTimer = 5;
public int waves;
public int currentWave;
public int waveEnemies;
public static int enemies;
public Transform[] spawnPoints;
void Start()
{
}
IEnumerator SpawnWavesE;
void FixedUpdate()
{
if (currentWave == 1)
{
StartCoroutine("SpawnWaves");
}
if (currentWave == 2)
{
StartCoroutine("SpawnWaves");
}
if (currentWave == 3)
{
StartCoroutine("SpawnWaves");
}
if (currentWave == 4)
{
StartCoroutine("SpawnWaves");
}
}
public IEnumerator SpawnWaves()
{
yield return new WaitForSeconds(startWait);
while (true)
{
for (int i = 0; i < waveEnemies; i++)
{
if (enemies < waveEnemies)
{
Debug.Log("Enmies:" + enemies);
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
PhotonNetwork.InstantiateSceneObject(Path.Combine("Enemy", "Enemy"), spawnPoints[spawnPointIndex].position, Quaternion.identity);
enemies += 1;
yield return new WaitForSeconds(spawnWait);
}
}
if (enemies <= 0)
{
Debug.Log("STARTING NEW WAVE");
currentWave += 1;
Debug.Log("Enmies:" + enemies);
Debug.Log("Wave: " + waves);
waveEnemies += 1;
yield return new WaitForSeconds(waveWait);
StopCoroutine("SpawnWaves");
}
}
}
Is there something i'm doing wrong??
Comment
Best Answer
Answer by myzzie · Jul 17, 2019 at 05:19 PM
Yeah you're doing quite a lot wrong here. First off, don't start a coroutine with a string, store it in a coroutine instead like this
Coroutine myCoroutine = StartCoroutine(SpawnWaves());
If you wish to stop the coroutine, do
StopCoroutine(myCoroutine);
Secondly, don't stop a coroutine inside a coroutine, figure out when to yield out of it instead e.g
While(enemies > 0)
Iv'e redone it a bit and did what you said like storing it, it works now but the only issue is it seems to be ignoring the if statment inside:
public IEnumerator SpawnWaves()
{
yield return new WaitForSeconds(startWait);
while (enemies < waveEnemies)
{
Debug.Log("Enmies:" + currentEnemies);
int spawnPointIndex = Random.Range(0, spawnPoints.Length);
PhotonNetwork.InstantiateSceneObject(Path.Combine("Enemy", "Enemy"), spawnPoints[spawnPointIndex].position, Quaternion.identity);
enemies += 1;
currentEnemies += 1;
yield return new WaitForSeconds(spawnWait);
if (currentEnemies == 0)
{
Debug.Log("STARTING NEW WAVE");
currentWave += 1;
Debug.Log("Enmies:" + enemies);
Debug.Log("Wave: " + waves);
waveEnemies += 1;
yield return new WaitForSeconds(1f);
StopCoroutine(myCoroutine);
}
}
nothing happens after, the game just continues