Unity3D 場景切換載入進度條實現
阿新 • • 發佈:2018-12-15
需要三個場景,場景A,場景B,場景C;
場景A:一個按鈕,點選載入場景B;
場景B:從A切換到C過度場景,載入進度條;
場景C:目標場景;
建立OnProgress.cs指令碼:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class OnProgress : MonoBehaviour { public void OnBtnClick() { Debug.Log("clicked"); Globe.nextSceneName = "MainScene";//目標場景名稱 SceneManager.LoadScene("Loading");//載入進度條場景 } }
建立一個panel,在panel下建立一個button,將OnProgress指令碼掛載到canvas,點選button,設定button屬性,繫結指令碼方法,點選加號,選擇canvas中剛才繫結指令碼中的方法OnBtnClick。至此,A場景完成。
建立B場景Loading:
Loading場景由兩部分組成,載入進度百分比和進度條:
文字就不說了,說明下進度條的實現,進度條實際是一個Image,設定Image Type為filled,fill Method為horizonal,這裡一定要新增source Image,否則下面的Image Type不會出來。
另外說下新增圖片,普通的圖片新增到assets中不能直接新增到Source Image中,需要對圖片進行設定,如下圖:
OK,再看進度條載入過程的實現:
建立AsyncLoadScene指令碼:
using UnityEngine; using System.Collections; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Globe { public static string nextSceneName; } public class AsyncLoadScene : MonoBehaviour {public Text loadingText; public Image progressBar; private int curProgressValue = 0; private AsyncOperation operation; // Use this for initialization void Start() { if (SceneManager.GetActiveScene().name == "Loading") { //啟動協程 StartCoroutine(AsyncLoading()); } } IEnumerator AsyncLoading() { operation = SceneManager.LoadSceneAsync(Globe.nextSceneName); //阻止當載入完成自動切換 operation.allowSceneActivation = false; yield return operation; } // Update is called once per frame void Update() { int progressValue = 100; if (curProgressValue < progressValue) { curProgressValue++; } loadingText.text = curProgressValue + "%";//實時更新進度百分比的文字顯示 progressBar.fillAmount = curProgressValue / 100f;//實時更新滑動進度圖片的fillAmount值 if (curProgressValue == 100) { operation.allowSceneActivation = true;//啟用自動載入場景 loadingText.text = "OK";//文字顯示完成OK } } }
將指令碼掛在到Loading場景的camera上面。設定物件:
這樣進度條載入場景就完成了,C場景就不介紹了,就是你要跳轉的目標場景。