Unity Coroutine无法跨场景工作

时间:2019-04-03 06:22:46

标签: c# unity3d coroutine

我正在调用如下所示的协程,该协程附加到在场景之间持久存在的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;
}

在上述游戏对象的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);
    }
}

尽管协程中的日志“将等待一段时间”正在打印,但是Debug.Log(“ coins length ==” + coin.Length)并非一直都在打印。我当然不会在可能导致协程以这种方式运行的整个游戏过程中销毁所述游戏对象。行为也不总是一致的,有时行得通,有时却行不通,我想你为什么不能下定决心。

我已经为此努力了很长时间,似乎无法解决这个问题,任何线索都可以解除我的思维障碍:/

1 个答案:

答案 0 :(得分:3)

不建议使用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());
    }
}