Unity實現(xiàn)場景加載功能
unity場景加載分為同步加載和異步加載,供大家參考,具體內(nèi)容如下
同步加載 loadScene
首先將前置工作做好。
創(chuàng)建一個項目工程,然后創(chuàng)建三個場景 loading00、loading01、loading02。每個場景分別創(chuàng)建一個cube、Sphere、Capsule 。然后打開File -> Build Settings, 然后將創(chuàng)建的 loading00、loading01、loading02拖拽到Scenes In Build中。如下圖:

然后再創(chuàng)建一個 loading.cs 腳本,然后寫上這段代碼:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class loading : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
// 同步加載場景
SceneManager.LoadScene(1, LoadSceneMode.Additive);
}
// Update is called once per frame
void Update()
{
}
}
SceneManager.LoadScene(1, LoadSceneMode.Additive);
第一個參數(shù)是表示加載的場景序號,第二個參數(shù)是 加載場景后,是否刪除舊場景。
場景序號就是在 BuildSettings 中的序號如下圖:

當然,第一個參數(shù)也可以寫場景的路徑:
SceneManager.LoadScene(“Scenes/loading01”, LoadSceneMode.Additive);
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class loading : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
// 同步加載場景
SceneManager.LoadScene("Scenes/loading01", LoadSceneMode.Additive);
}
// Update is called once per frame
void Update()
{
}
}
與上述代碼想過是一致的。
異步加載
異步加載需要先介 AsyncOperation 類
SceneManager.LoadSceneAsync(1, LoadSceneMode.Additive) 這個是異步加載的函數(shù),其參數(shù)的用法跟同步加載的用法一致,然后,返回值 是一個 As yncOperation 類。
AsyncOperation 的用處:
- AsyncOperation.isDone 這個是用來判斷加載是否完成。這個屬性是加載完并且跳轉(zhuǎn)成功后才會變成完成
- AsyncOperation.allowSceneActivation 這個是加載完后,是否允許跳轉(zhuǎn),當為false時,即使場景加載完了,也不會跳轉(zhuǎn)
- AsyncOperation.progress 這個時表示加載場景的進度。實際上的值時 0 - 0.9, 當值為0.9的時候,場景就已經(jīng)加載完成了。
我們要異步加載場景的話,一般都是需要用協(xié)程一起工作
代碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class loading : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
StartCoroutine(Load());
}
IEnumerator Load()
{
AsyncOperation asyncOperation = SceneManager.LoadSceneAsync(1, LoadSceneMode.Additive);
asyncOperation.allowSceneActivation = false; // 這里限制了跳轉(zhuǎn)
// 這里就是循環(huán)輸入進度
while(asyncOperation.progress < 0.9f)
{
Debug.Log(" progress = " + asyncOperation.progress);
}
asyncOperation.allowSceneActivation = true; // 這里打開限制
yield return null;
if(asyncOperation.isDone)
{
Debug.Log("完成加載");
}
}
// Update is called once per frame
void Update()
{
}
}
異步和同步的區(qū)別
異步不會阻塞線程,可以在加載過程中繼續(xù)去執(zhí)行其他的一些代碼,(比如同時加載進度)而同步會阻塞線程,只有加載完畢顯示后才能繼續(xù)執(zhí)行之后的一些代碼。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#利用反射來判斷對象是否包含某個屬性的實現(xiàn)方法
這篇文章主要介紹了C#利用反射來判斷對象是否包含某個屬性的實現(xiàn)方法,很有借鑒價值的一個技巧,需要的朋友可以參考下2014-08-08
C#數(shù)據(jù)綁定(DataBinding)簡單實現(xiàn)方法
這篇文章主要介紹了C#數(shù)據(jù)綁定(DataBinding)簡單實現(xiàn)方法,以簡單實例形式簡單分析了C#實現(xiàn)數(shù)據(jù)綁定與讀取的方法,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08

