- Home /
Coroutines Cannot be Stopped Outside Initiating class
Can coroutines only be stopped inside the script that started them? Even if they are both attached to the same game object?
For example, attach both of these scripts to the same GO and the code below will loop endlessly:
public class RunCoroutine : MonoBehaviour {
void Start()
{
StartCoroutine("Test");
}
IEnumerator Test()
{
int i=0;
while (true)
{
i++;
print("Running loop " + i);
yield return null;
}
}
}
public class EndCoroutine : MonoBehaviour {
void Update()
{
if (Time.time > 3f)
{
StopAllCoroutines();
}
}
}
But moving StopAllCoroutines into the first script will work as expected.
public class RunCoroutine : MonoBehaviour {
void Start()
{
StartCoroutine("Test");
}
void Update()
{
if (Time.time > 3f)
{
StopAllCoroutines();
}
}
IEnumerator Test()
{
int i=0;
while (true)
{
i++;
print("Running loop " + i);
yield return null;
}
}
}
maybe pass a value into the initiating class to control when to stop it, from the other class using a global var.
Answer by slavo · Sep 05, 2014 at 03:31 PM
Corutine run on Monobehaviour instance, so it can be stoped only by same instance that start it.
You can call function that tell class to stop corutine.
public class RunCoroutine : MonoBehaviour {
void Start()
{
StartCoroutine("Test");
}
IEnumerator Test()
{
int i=0;
while (true)
{
i++;
print("Running loop " + i);
yield return null;
}
}
public void StopCorutines()
{
StopAllCoroutines();
}
}
public class EndCoroutine : MonoBehaviour {
public RunCoroutine script;
void Update()
{
if (Time.time > 3f)
{
script.StopCorutines();
}
}
}
Yeah, that's what I ended up doing. Thanks for your reply!
you can also stop is with the string of the corutine but it needs to be started with a string.
Your answer
![](https://koobas.hobune.stream/wayback/20220613162352im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Coroutine gets stuck randomly? 1 Answer
Make sure levels assets are loaded before switching? 1 Answer
Loop Coroutine For A Demo Mode 1 Answer