我正在调用下面显示的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以这种方式行事。这种行为也不一致,有时它会起作用,有时却不行,我想你为什么不能下定决心。
我一直在敲打这个问题很长一段时间似乎无法解决这个问题,任何领导都会被提升我的心理障碍:/
不推荐使用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());
}
}