如何在unity中使场景加载暂停一秒钟



下面是我在Unity (Asyn)中加载下一个场景的代码。它工作得很好。但我需要它在加载后等待一秒钟才能显示场景。怎么做

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class LoadingScreenScript : MonoBehaviour
{
[SerializeField]
private Image _progressBar;
// Start is called before the first frame update
void Start()
{
StartCoroutine(LoadAsyncOperatiom());   
}

IEnumerator LoadAsyncOperatiom()
{
AsyncOperation gameLevel = SceneManager.LoadSceneAsync(2);
while (gameLevel.progress < 1)
{
_progressBar.fillAmount = gameLevel.progress;
yield return new WaitForEndOfFrame();
} 
transition.SetTrigger("Start");

//yield return new WaitForSeconds(transitionTime);
}
}

所以默认情况下,Unity在加载场景后立即进入场景(并离开旧场景)。但是,您可以使用AsyncOperation.allowSceneActivation更改此行为。

需要注意的是,场景加载的进度将在[0f-0.9f]之间,其中0.9f表示完全加载但不活动的场景。它不会达到1.0f,直到你设置AsyncOperation。allowSceneActivation为true,允许场景激活

因此,当等待场景加载时,您必须检查gameLevel.progress < 0.9f,而不是1

你可以这样修改你的代码:

IEnumerator LoadAsyncOperatiom()
{
AsyncOperation gameLevel = SceneManager.LoadSceneAsync(2);
gameLevel.allowSceneActivation = false; // stop the level from activating
while (gameLevel.progress < 0.9f)
{
_progressBar.fillAmount = gameLevel.progress;
yield return new WaitForEndOfFrame();
} 
transition.SetTrigger("Start");

yield return new WaitForSeconds(transitionTime);
gameLevel.allowSceneActivation = true; // this will enter the level now
}

它应该可以工作。

存在一个著名的BUG,它要求把

yield return null;

在任何其他代码行之前出现在例程的开头。我发现这在UNITY 2020.3.34f1中是强制性的。在UNITY DOC中也使用相同的顺序。协程应该看起来像这样:

{
yield return null;
AsyncOperation gameLevel = SceneManager.LoadSceneAsync(2);
gameLevel.allowSceneActivation = false; // stop the level from activating
while (gameLevel.progress < 0.9f)
//...
}

@Jay在这里写的是gameLevel。进度只能达到0.9f

P.S>重要的是要记住,如果你做两个或更多的async操作;(两个异步加载或一个异步加载和另一个异步卸载)并暂停("allowSceneActivation = false")完成第一个异步操作(见链接UnityDocupper):

AsyncOperation队列已停止

最新更新