在U3D開發(fā)過(guò)程中經(jīng)常使用到多場(chǎng)景的切換,有同步SceneManager.LoadScene()和異步SceneManager.LoadSceneAsync()兩種方法,同步的話一般就會(huì)卡住界面直到加載完成,使用異步的話一般都做一個(gè)加載的進(jìn)度條,每次切換的時(shí)候都需要一個(gè)加載動(dòng)畫,所以需要建一個(gè)專門的過(guò)渡加載場(chǎng)景來(lái)進(jìn)行統(tǒng)一加載,也可以避免場(chǎng)景直接切換出現(xiàn)的黑屏。
一、建立一個(gè)單例進(jìn)行切換,在項(xiàng)目代碼的任何位置都可以調(diào)用
public class LoadSceneManager
{
private static LoadSceneManager instance;
public static LoadSceneManager Instance
{
get {
if (instance == null)
{
instance = new LoadSceneManager();
}
return instance;
}
}
public string nextSceneName;
//異步加載
public void LoadSceneAsync(string sceneName)
{
Debug.Log("LoadSceneAsync:" + sceneName);
nextSceneName = sceneName;
SceneManager.LoadScene("LoadingScene");
}
public void LoadScene(string sceneName)
{
Debug.Log("LoadScene:" + sceneName);
SceneManager.LoadScene(sceneName);
}
}
使用的時(shí)候直接使用LoadSceneManager.Instance.LoadSceneAsync("SecondScene");
二、異步加載的過(guò)程
要做個(gè)進(jìn)度條然后進(jìn)行管理,代碼很簡(jiǎn)單就不說(shuō)了
public class LoadingController : MonoBehaviour
{
public Slider loadingSlider;
public TMP_Text loadingText;
private AsyncOperation asyncOperation;
private float operationProgress;
// Start is called before the first frame update
void Start()
{
loadingSlider.value = 0.0f;
if (SceneManager.GetActiveScene().name == "LoadingScene")
{
StartCoroutine("LoadingScene");
}
}
IEnumerator LoadingScene()
{
asyncOperation = SceneManager.LoadSceneAsync(LoadSceneManager.Instance.nextSceneName);
asyncOperation.allowSceneActivation = false;
yield return asyncOperation;
}
// Update is called once per frame
void Update()
{
operationProgress = asyncOperation.progress;
//最大值只到0.9,后面有進(jìn)行插值運(yùn)算更新
if (Mathf.Approximately(operationProgress, 0.9f))
{
operationProgress = 1;
}
if (Mathf.Approximately(operationProgress, 0.6f))
{
System.Threading.Thread.Sleep(5000);
}
UpdateLoadingUI(operationProgress);
}
private void UpdateLoadingUI(float value)
{
if (operationProgress != loadingSlider.value)
{
loadingSlider.value = Mathf.Lerp(loadingSlider.value, operationProgress, Time.deltaTime * 2);
if (Mathf.Approximately(operationProgress, operationProgress))
{
loadingSlider.value = operationProgress;
}
}
Debug.Log("Progress:" + loadingSlider.value);
if (loadingText != null)
{
loadingText.text = Mathf.Round(loadingSlider.value * 100) + "%";
}
//自動(dòng)換場(chǎng)景
if (Mathf.Approximately(loadingSlider.value, 1.0f))
{
asyncOperation.allowSceneActivation = true;
}
}
}
三、demo鏈接
https://download.csdn.net/download/emailforwei/87329335文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-634441.html
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-634441.html
到了這里,關(guān)于Unity 3D開發(fā)--SceneManager場(chǎng)景管理(異步使用同一個(gè)過(guò)渡場(chǎng)景)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!