Unity Coroutine无法跨场景工作 [英] Unity Coroutine not working across scenes
问题描述
我正在调用如下所示的协程,该协程附加到在场景之间持久存在的DontDestroyOnLoad
对象.
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;
}
在上述游戏对象的OnLevelWasLoaded
事件中调用此协程,该事件在清醒时设置为DontDestroyOnLoad
,如下所示.
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);
}
}
尽管协程中的日志将等待一段时间"正在打印,但是Debug.Log("coins length ==" + coin.Length)并非一直都在打印.我当然不会在可能导致协程以这种方式运行的整个游戏过程中销毁所述游戏对象.行为也不总是一致的,有时行得通,有时行不通,我想你为什么不能下定决心.
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 :/
推荐答案
不推荐使用OnLevelWasLoaded,请考虑使用sceneLoaded事件:
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());
}
}
这篇关于Unity Coroutine无法跨场景工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!