Unity非同步載入進度條
阿新 • • 發佈:2021-06-20
先上程式碼:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; #region 佛祖保佑 /* _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . __ ."" '< `.___\_<|>_/___.' >'"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ======`-.____`-.___\_____/___.-`____.-'====== `=---=' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 佛祖保佑 永無BUG */ #endregion public class AsyncLoadScene : MonoBehaviour { public static string NEXTSCENENAME = "ChooseLevelScene"; private Text text_loadProgress; private RectTransform rectTransform_progressBar; private AsyncOperation asyncLoadScene; private float progressValue; private void Start() { text_loadProgress = transform.Find("Text").GetComponent<Text>(); rectTransform_progressBar = transform.Find("Image").GetComponent<RectTransform>(); asyncLoadScene = SceneManager.LoadSceneAsync(NEXTSCENENAME); asyncLoadScene.allowSceneActivation = false; } private void Update() { if(text_loadProgress && rectTransform_progressBar) { progressValue = Mathf.Lerp(progressValue, asyncLoadScene.progress / 0.9F, Time.deltaTime); text_loadProgress.text = (progressValue * 100F).ToString("F0") + "%"; rectTransform_progressBar.sizeDelta = new Vector2(progressValue * 1280F, 85F); if(rectTransform_progressBar.sizeDelta.x > 1275F) asyncLoadScene.allowSceneActivation = true; } } }
接著如果你感到迷惑,請看如下游戲物件層級:
指令碼掛在Panel物件上
那如何使用她呢?
public GameObject Prefab_LoadScene; private void Click_play(){ Instantiate(Prefab_LoadScene); } //--------------或者請看如下---------------- public GameObject Prefab_LoadScene; private void Click_play(){ GameObject loadScener = Instantiate(Prefab_LoadScene); //區別就是這一個可以自定義下一場景名,而上一個雖然只有一行程式碼,但下一場景名是預設的 loadScener.transform.Find("Panel").GetComponent<AsyncLoadScene>().NEXTSCENENAME = "下一場景名"; }