- Home /
I need to Stop and Restart a Co-Routine at anytime
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;
}
Have you tried storing the coroutines in attributes of your class ? I suspect the following : When calling StopCoroutine (SpawnZigZag (2)); you "instantiate" a new coroutine and you try to stop it, but what you wanted to do is stoppping the coroutine "instantiated" in the StartCoroutine earlier
private IEnumerator spawnZigZagCoroutine ;
void Start()
{
spawnZigZagCoroutine = SpawnZigZag(2) ;
}
// ...
IEnumerator level$$anonymous$$anagement()
{
// ...
StartCoroutine( spawnZigZagCoroutine );
// ...
StopCoroutine( spawnZigZagCoroutine );
// ...
}
Answer by ghostravenstorm · May 18, 2017 at 07:07 AM
Bump
I too am having this problem designing timers. Using Start and Stop on a coroutine running a timer seems to increment its speed everytime Start is called using the IEnumerator variable as the parameter
Your answer
Follow this Question
Related Questions
CancelInvoke cant cancell,Updating InvokeRepeating 1 Answer
Is it possible to invoke a button Press With a Coroutine? 1 Answer
StartCoroutine by another class (Coroutine inside Coroutine - Instance class) 1 Answer
NullReferenceException in StartCoroutine 1 Answer
How to stop a coroutine started in Script A from within Script B 1 Answer