简体   繁体   English

Unity Coroutine无法跨场景工作

[英]Unity Coroutine not working across scenes

I am calling a Coroutine shown below, which is attached to a DontDestroyOnLoad objects that persists across scenes. 我正在调用如下所示的协程,该DontDestroyOnLoad附加到在场景之间持久存在的DontDestroyOnLoad对象。

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. 在上述OnLevelWasLoaded事件中调用此协程,该事件在唤醒时设置为DontDestroyOnLoad ,如下所示。

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. 当协程中的日志“将等待一段时间”被打印时,Debug.Log(“ coins length ==” + coin.Length)并不会一直打印。 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 :/ 我已经为此努力了很长时间,似乎无法解决这个问题,任何线索都将解除我的精神障碍:/

OnLevelWasLoaded is deprecated, consider using sceneLoaded event: 不建议使用OnLevelWasLoaded,请考虑使用sceneLoaded事件:

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());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM