Unity Coroutine无法跨场景工作

问题描述 投票:2回答:1

我正在调用下面显示的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;
}

这个Coroutine在所述游戏对象的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);
    }
}

当Coroutine中的日志“将等待一段时间”被打印时,Debug.Log(“币长==”+ coins.Length)不会一直打印。我肯定没有在游戏的整个过程中摧毁所说的游戏对象,这可能导致Coroutine以这种方式行事。这种行为也不一致,有时它会起作用,有时却不行,我想你为什么不能下定决心。

我一直在敲打这个问题很长一段时间似乎无法解决这个问题,任何领导都会被提升我的心理障碍:/

c# unity3d coroutine
1个回答
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());
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.