我正在调用如下所示的协程,它附加到跨场景持续存在的 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) 并不总是被打印。我当然不会在整个游戏过程中销毁所述游戏对象,这可能会导致协程出现这种行为。行为也不一致,有时有效,有时无效,我就想你为什么不能下定决心。
我已经为此烦恼了很长时间,似乎无法解决这个问题,任何线索都将不胜感激,以解除我的心理障碍:/
最佳答案
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());
}
}
关于c# - Unity协程无法跨场景工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55488344/