- Home /
Simple coroutine doesn't resume after setting renderer.enabled to false
Hello everyone,
I'm trying to make a bonus that starts with a trigger and last for one second. I've made a coroutine for that. here's my simplified code.
Here's what I get in the console : About to StartCoroutine disable about to yield return WaitForSeconds(1) back from StartCoroutine
And never get the "Just waited 1 second" log, as long as I have the ligne renderer.enabled = false or gameObject.SetActive(false). When I remove that line everyhting works perfectly... But I still need to hide the gameObjectand disable it's collider.
void OnTriggerEnter2D ()
{
activated = true;
Debug.Log ("About to StartCoroutine");
StartCoroutine (MyCoroutine ());
Debug.Log ("Back from StartCoroutine");
}
IEnumerator MyCoroutine ()
{
this.Disable ();
Debug.Log ("about to yield return WaitForSeconds(1)");
yield return new WaitForSeconds (1);
Debug.Log ("Just waited 1 second");
}
void Disable ()
{
Debug.Log ("disable");
this.collider2D.enabled = false;
this.renderer.enabled = false;
//gameObject.SetActive (false);
}
Do you have any idea ?
$$anonymous$$ill the this. this.collider2D is equivalent to collider2D
Answer by Kiwasi · Sep 29, 2014 at 11:45 PM
Coroutines will only continue to run on an active GameObject.
With this set up as is you should see the following output
About to StartCoroutine
disable
about to yield return WaitForSeconds(1)
Back from StartCoroutine
1 second delay
Just waited 1 second
Once you call gameObject.SetActive(false) you will stop execution at the first yield statement
There are a couple of options to resolve
Call StartCoroutine on a separate GameObject that remains active
Disable all components on your GameObject. Be careful with this approach, it has the potential to mess up the behaviour of other components if not done correctly.
Thank you a lot for your answer. I moved the coroutine to another gameObject that will remain active in the scene and everything's resolved.
Your answer
Follow this Question
Related Questions
How to use corutines in a class 1 Answer
How to start a coroutine from Update. 4 Answers
Coroutine does not seem to work 1 Answer
Coroutine couldn't be started becuase inactive 0 Answers
coroutine spamming webserver which then stops replying 2 Answers