Unity Coroutine not working across scenes

三世轮回 提交于 2019-12-24 04:31:40

问题


I am calling a Coroutine shown below, which is attached to a DontDestroyOnLoad objects that persists across scenes.

IEnumerator InitMaxScore()
{
    Debug.Log("will wait for some time");
    yield return new WaitForSeconds(1);
    GameObject[] coins = GameObject.FindGameObjectsWithTag("Coin");
    Debug.Log("coins length == " + coins.Length);
    if (coins.Length > 0)
    {
        maxScoreInitialized = true;
        maxScore = score + coins.Length * 10;
        foreach (GameObject healthPickup in GameObject.FindGameObjectsWithTag("Health"))
        {
            maxScore += healthPickup.GetComponent<Pickups>().pointsForLifePickup;
        }
        Debug.Log("maxScore inti == " + maxScore);
    }
    yield return null;
}

This Coroutine is called in the OnLevelWasLoaded event of the said gameobject which is set to DontDestroyOnLoad on awake as shown below.

private void Awake()
{
    int numGameSessions = FindObjectsOfType<GameSession>().Length;
    if (numGameSessions > 1)
    {
        Destroy(gameObject);
    }
    else
    {
        DifficultyManagement.setDifficulty(Difficulty.One); // start the game with diff one always
        DontDestroyOnLoad(this.gameObject);
    }
}

While the log "will wait for some time" in the Coroutine is getting printed, Debug.Log("coins length == " + coins.Length) is not getting printed all the times. I am certainly not destroying the said gameobject for the entire duration of my game that might have caused the Coroutine to behave this way. The behaviour is not consistent either, sometimes it works, sometimes it does not, and I am like why can't you make up your mind.

I have been banging my head on this for a long time and could not seem to fix this, any leads would be appreciated to lift my mental block :/


回答1:


OnLevelWasLoaded is deprecated, consider using sceneLoaded event:

using UnityEngine.SceneManagement;

private void Awake()
{
    int numGameSessions = FindObjectsOfType<GameSession>().Length;
    if (numGameSessions > 1)
    {
        Destroy(gameObject);
    }
    else
    {
        DifficultyManagement.setDifficulty(Difficulty.One); // start the game with diff one always
        DontDestroyOnLoad(this.gameObject);
        SceneManager.sceneLoaded += (scene, mode) => StartCoroutine(InitMaxScore());
    }
}


来源:https://stackoverflow.com/questions/55488344/unity-coroutine-not-working-across-scenes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!