【发布时间】:2019-08-24 13:56:02
【问题描述】:
我正在调用如下所示的协程,它附加到在场景中持续存在的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()函数中使用StartCoroutine(InitMaxScore()); -
奇怪的是,自从我发布这个问题以来,它一直运行良好。但在我的构建中不起作用。
-
这太奇怪了,协程在 Unity 中按预期工作。我在没有任何代码或场景更改的情况下重新启动了 Unity,但它又坏了。
-
是否会多次加载包含此脚本的场景?