当我的游戏完成时,我如何启用一个异步函数



作为一个初学者/学习程序员,这一直困扰着我。我一直在尝试这样做,当我的游戏使用异步方法完成加载时,它会加载一个按钮,这样你就可以继续了。相反,它完全忽略了这个功能,导致按钮一直在那里,当你过早按下时就会出现故障。我的代码就在这里;我该怎么解决这个问题?

IEnumerator LoadSceneAsynchronously(int levelIndex)
{
AsyncOperation operation = SceneManager.LoadSceneAsync(levelIndex);
while (!operation.isDone)
{
Debug.Log(operation.progress);
loading.GetComponent<Animator>().Play("loading");
text.GetComponent<Animator>().Play("idle");
yield return null;
}
if (!operation.isDone)
{
yield return new WaitForSeconds(5);
loading.GetComponent<Animator>().Play("loading disappear");
text.GetComponent<Animator>().Play("appear text");
text.GetComponent<Animator>().Play("blink text")
yield return null;
}
}
public void DestroyLoading()
{
gameObject.SetActive(false);
GameIsDoneLoading = true;
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && !GameIsDoneLoading == true)
{
Debug.Log("Space key was pressed.");
text.GetComponent<Animator>().Play("disappear text");
logo.GetComponent<Animator>().Play("fpsa logo disappear");
}
}

当在Coroutine中"yield"时,代码执行会在下一帧中返回到完全相同的位置,因此在上面的while循环中,它只会在每一帧中检查该条件,然后向下一帧屈服。我相信你想做的是…

IEnumerator LoadSceneAsynchronously(int levelIndex)
{
// start the async loading
AsyncOperation operation = SceneManager.LoadSceneAsync(levelIndex);
// start playback of your animations in the scene
loading.GetComponent<Animator>().Play("loading");
text.GetComponent<Animator>().Play("idle");

// now wait for the scene to fully load
while (!operation.isDone)
{
Debug.Log(operation.progress);
yield return null;
// after yielding, we return here and repeat the while
// loop on the next frame
}
// we have broken free of the while loop so the level has now fully loaded
// and operation.isDone is now true
// play some other animations to fade out the loading system?
loading.GetComponent<Animator>().Play("loading disappear");
text.GetComponent<Animator>().Play("appear text");
text.GetComponent<Animator>().Play("blink text")
// I'm assuming these animations take about 5 seconds to complete?
// so just wait in here for 5
yield return new WaitForSeconds(5);
// loading level and animations all done...proceed to games
DestroyLoading();
}

最新更新