Coroutine doesn't invoke my function after reload level

Hey,

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

yield return new WaitForSeconds (time);

Do you know why?
Thanks

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:

  1. You can set a static “flag” variable that your component checks at Start():
private static bool doThatThingOnStart = false;
void Start() {
if (doThatThingOnStart) {
DoThatThing();
doThatThingOnStart = false;
}
}

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).

  1. 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.

@StarMania thanks for help.

I’ve just found the answer. I stoped time when I clicked Pause Button

Time.timeScale = 0;

When I reload Game timeScale is still 0.

I put Time.timeScale = 1; in my Start() function for restart it. Now it works ok.

Hello,

I have the same problem, but my timeScale is still 1.

Any other solution?

Are You Find Any Solution ?

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. :slight_smile:
The last message here was over a year ago and that person was bumping an older message, etc… you get the idea :slight_smile:

1 Like

Thank you so much for your reply. Actually, I find My Solution :slight_smile: Thank you again :slight_smile: