Unity實現(xiàn)場景加載功能
unity場景加載分為同步加載和異步加載,供大家參考,具體內容如下
同步加載 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 這個是用來判斷加載是否完成。這個屬性是加載完并且跳轉成功后才會變成完成
- AsyncOperation.allowSceneActivation 這個是加載完后,是否允許跳轉,當為false時,即使場景加載完了,也不會跳轉
- AsyncOperation.progress 這個時表示加載場景的進度。實際上的值時 0 - 0.9, 當值為0.9的時候,場景就已經加載完成了。
我們要異步加載場景的話,一般都是需要用協(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; // 這里限制了跳轉 // 這里就是循環(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í)行之后的一些代碼。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
VS2019下安裝和破解?DevExpress?19.2?插件的詳細教程
這篇文章主要介紹了VS2019?安裝并破解?DevExpress?19.2?插件的詳細教程,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03C# Winform使用擴展方法實現(xiàn)自定義富文本框(RichTextBox)字體顏色
這篇文章主要介紹了C# Winform使用擴展方法實現(xiàn)自定義富文本框(RichTextBox)字體顏色,通過.NET的靜態(tài)擴展方法來改變RichTextBox字體顏色,需要的朋友可以參考下2015-06-06