- Home /
How to stop coroutines, when paused
I wanted to know that can coroutines be stopped using any function (like StopCoroutine) when they are currently suspended or paused, (using waitforseconds or by any other means) in c#? . And if so please tell me how.
Answer by sh_code · Jan 17, 2019 at 02:15 PM
you answered your own question within itself =D
Coroutine theOneIWantToStopAnytime = StartCoroutine();
StopCoroutine(theOneIWantToStopAnytime);
this cancels them from the outside, immediately, regardless of what state is their execution in.
oh, but, btw, pure c# doesn't have coroutines. coroutines are Unity's invention
Not really a Unity invention ^^. All the required magic is pure C# compiler magic. Also coroutines can only be stopped while it is suspended / yielded since it's cooperative multitasking. Since the scripting environment is singlethreaded there is no way you can stop a coroutine while it is currently executing. A coroutine could stop itself, but it will actually stop when you reach the next yield or when you simply let the coroutine finish.
Answer by surfuay · Jan 18, 2019 at 02:03 AM
are you trying to pause them?
if so you can say
time.timeScale = 0;
and just put that wherever you're trying to temporarily suspend the coroutine, then where ever you want to pick it back up say
time.timeScale = 1;
@surfuay but will the rest of the program or scripts continue running?
yes, time.timescale = 0 will suspend everything
you can circumvent that by adding waitforrealseconds on any coroutines you don't want suspended
you can even make a player move at normal rate while everything else is "frozen" by giving the player an if or a while statement such as
if (coroutines frozen == true) time.timescale = 1 //this would be in the player script
but you can make a bool that is set to true anytime you freeze the coroutines and then make an if statement for anywhere else you want to circumvent that pausing
Your answer
Follow this Question
Related Questions
WaitForSeconds Not Working 4 Answers
Can't get past WaitForSeconds in my coroutine 1 Answer
IEumerator not recognising when a bool has switched 1 Answer
Why do you use Coroutines and how do you use them? 1 Answer
WaitforSeconds woes 3 Answers