- Home /
Coroutine Not Completely executing
I'm been stuck on this silly bug for some time now and I can't find an answer why it may have happened. I'm trying to do a very simple which is deactivating a panel GameObject using a coroutine (to allow the button SFX to play). Heres what I'm trying to do:
public class ExampleScript : MonoBehaviour
{
public GameObject confirmPanel;
public void CancelReturnToMenu()
{
StartCoroutine(CancelReturnToMenuTime());
}
public IEnumerator CancelReturnToMenuTime()
{
yield return new WaitForSeconds (0.25f);
confirmPanel.SetActive(false);
}
}
I'm calling the function CancelReturnToMenu() on my button via an OnClick event in Unity.
I'm not sure why this is not working, I'm not doing anything else. The coroutine is waiting 0.25 sec because I can hear the sound effect, however I'm not sure why the code after that line is not executing.
Thanks for the help
Answer by xxmariofer · Jun 28, 2019 at 07:42 AM
This is by far the most common error i have seen in unity answers, there are 2 posibilitys, you are destroying the gameobject attached to the examplescript behaviour, or you are desactivating it
Yeah I've actually seen a couple questions regarding the same issue, but I don't really understand. Just to make sure, the coroutine has to be completely executed then I can deactivate the gameobject with this script attached right??
I thought this might occur only you Destroy/deactivate the gameobject before WaitForSeconds
Edit: Ok I get it, just don't deactivate anything in a coroutine...
Can you show me an example of what I should be doing in this case?
You have to handle the corroytine from a script thats not attached to the gameobject that you desactivate, you can start the corroytine from anywhere, or desactivate the gameobject AFTER all the yield instructions
Sorry, you are a bit wrong. Coroutine can be handled everywhere except deactivated objects. Coroutine can deactivate itself game object, but coroutine cant activate itself game object, because it dosnt work on deactivated game objects. Every time, when game object is deactivated, it stops all coroutines.
Answer by Kennai · Jun 28, 2019 at 09:28 AM
Hi, @Ryox92! Are you sure, you do not deactivate game object with ExampleScript, when you click button? Maybe your button do 2 things - call func CancelReturnToMenu and deactivate game object with ExampleScript?
Actually I was also deactivating the GameObject with the ExampleScript, I'll make sure its done somewhere else to avoid such problems in the future. Thanks a lot for your help @$$anonymous$$ennai