My problem is that co-routines are overlapping eachother. I have even called StopAllCoroutines right before starting a new one, yet they still overlap. How can I ensure that only a single co-routine exists at one time?
Can anyone explain why they are overlapping even though I’m calling StopAllCoroutines before starting a new one?
void OnEnable() {
if (!isRunning) {
StopAllCoroutines ();
StartCoroutine (levelManagement ());
}
}
void Update() {
if (LoseGame.loseGame == true) {
isRunning = false;
this.enabled = false;
}
}
IEnumerator levelManagement() {
isRunning = true;
while (isRunning) {
//Level 1
InvokeRepeating ("SpawnRandomCubes", 0.25f, 0.25f);
yield return new WaitForSeconds (10f);
CancelInvoke ("SpawnRandomCubes");
InvokeRepeating ("SpawnSingleEntries", 1.5f, 1.5f);
yield return new WaitForSeconds (4.5f);
CancelInvoke ("SpawnSingleEntries");
InvokeRepeating ("SpawnRandomCubes", 0.25f, 0.25f);
yield return new WaitForSeconds (10f);
CancelInvoke ("SpawnRandomCubes");
//Level 2
StartCoroutine(SpawnZigZag(2));
yield return new WaitForSeconds (10f);
StopCoroutine (SpawnZigZag (2));
InvokeRepeating ("SpawnRandomCubes", 0.2f, 0.2f);
yield return new WaitForSeconds (15f);
CancelInvoke ("SpawnRandomCubes");
}
yield break;
}