Why coroutine stops working/executing

2019-03-01 12:58发布

I have a 3 second countdown timer which is activated when game is unpaused. I had it working correctly a couple of days ago but now it doesn't work anymore. It gets blocked on the number 3. This is the code:

IEnumerator Timer() {

    Time.timeScale = 0;

    objectWithGSScript.scoreText.fontSize = 300;

    objectWithGSScript.scoreText.text = "" + 3;
    yield return WaitOneSecond();

    objectWithGSScript.scoreText.text = "" + 2;
    yield return WaitOneSecond();

    objectWithGSScript.scoreText.text = "" + 1;
    yield return WaitOneSecond();

    objectWithGSScript.scoreText.text = "Go!";
    yield return WaitOneSecond();

    Time.timeScale = 1f;

    objectWithGSScript.scoreText.text = objectWithGSScript.score.ToString();

}

IEnumerator WaitOneSecond() {
    float start = Time.realtimeSinceStartup;
    while (Time.realtimeSinceStartup < start + 1f) {
        print("entered");
        yield return null;
    }
}

It prints "entered" only once, it seems it exit from the coroutine, like it's returning null forever.

What could be the problem?

Any help would be appreciated.

1条回答
姐就是有狂的资本
2楼-- · 2019-03-01 13:18

The function in your code is perfectly fine. No, it does not and should not stop at the number 3.

These are the possible reasons why it is behaving like it is getting stopped at the number 3.

1.You are calling StopCoroutine or or StopAllCoroutines. Please check that you are not stopping the coroutines. If you are when it is running, then it will behave this way.

2.You are destroying the script or GameObject this script is attached to. Check where you call the Destroy(gameObject);, Destroy(this); or something similar. If the script is destroyed, the coroutine should stop running.

Remember that you can destroy a script from another script so check all scripts.

3.You disabled the GameObject that his script is attached to. When you disable a GameObject, the coroutine stops working. Check that you don't have gameObject.SetActive(false); or anything with SetActive(false); that disables that GameObject.

4.If you have a coroutine function in ScriptA and then starts that coroutine from ScriptB, if you destroy ScriptB, the coroutine from ScriptA will freeze at the yield return statement. It is important that you know this.

5. Null problem...

Maybe the objectWithGSScript.scoreText.text is not null. You must check each variable and make sure that they are not null. The if stametement is fine but a good shortcut is this:

UnityEngine.Debug.Log(objectWithGSScript);
UnityEngine.Debug.Log(objectWithGSScript.scoreText);
UnityEngine.Debug.Log(objectWithGSScript.scoreText.text);

then you can do:

objectWithGSScript.scoreText.fontSize = 300;
objectWithGSScript.scoreText.text = "" + 3;

I can't think of any other possible reason why this is happening but check all those five things mentioned above.

查看更多
登录 后发表回答