I have a problem with Coroutine. I have two scenes: Menu and Game.
In the Game scene I have a button “return to menu” and in the Menu I have button play ( what brings me back to the Game scene).
I use two different scripts in those scenes.
In the Game I have:
private IEnumerator myCoroutine;
public void myFunction() { ...... }
void Start ()
{
myCoroutine = WaitAndDo( 0.4f, myFunction);
StartCoroutine( myCoroutine );
}
IEnumerator WaitAndDo(float time, DelayedMethod method)
{
while (true)
{
yield return new WaitForSeconds (time);
method ();
}
}
It works fine when: PlayButton (Menu) → load level Game
But when I try to reload Game:
PlayButton ( in Menu) → load level Game → Back To Menu Button → PlayButton ( in Menu) → load level Game
method ();
doesn’t invoke.
I debugged it in MonoDevelop and it stops in
When you run a coroutine, it’s being run on the object. If that object is destroyed (and, I think, also when it is deactivated), then it stops running. I see 2 simple options:
You can set a static “flag” variable that your component checks at Start():
And make sure that doThatThingOnStart is set to true if your script is waiting to DoThatThing(). static variables are per class (not per object), and persist when all your objects have been destroyed (though not across player sessions).
You can use DontDestroyOnLoad to make your object persist across scenes, and the coroutine will continue. Be aware that when you re-load your scene you will likely now have two of these things in the scene, so you may have to code around that.
If you have an issue that you believe was not solved in this thread, create your own and post your code and whatever’s happening and/or wrong.
The last message here was over a year ago and that person was bumping an older message, etc… you get the idea