Unity,Loading界面,异步加载场景
加载新场景时,需要加载大量模型外部文件等,比较耗时,又不能让画面卡住不动;
很多时候会做一个加载界面显示读条;
这个加载条是个UI物体,可以自行添加替换UI素材;
非常简直,就不赘述了;
一个slider条,progress为异步百分比;
限制读条3s结束,小于3s等待;
注意异步读条progress到不了1,所以0.9判断加载完成;
public class Loading : MonoBehaviour { public string scenceName; AsyncOperation async; public Slider m_pProgress; private int progress = 0; private float time = 3f; private float startTime = 0; private void Start() { StartCoroutine(LoadScenes()); startTime = Time.time; } IEnumerator LoadScenes() { int nDisPlayProgress = 0; async = SceneManager.LoadSceneAsync(scenceName); async.allowSceneActivation = false; while (async.progress < 0.9f) { progress = (int)async.progress * 100; while (nDisPlayProgress < progress) { ++nDisPlayProgress; m_pProgress.value = (float)nDisPlayProgress / 100; yield return new WaitForEndOfFrame(); } yield return null; } progress = 100; while (nDisPlayProgress < progress) { ++nDisPlayProgress; m_pProgress.value = (float)nDisPlayProgress / 100; yield return new WaitForEndOfFrame(); } float temp = Time.time - startTime; if (temp < time) yield return new WaitForSeconds(time - temp); async.allowSceneActivation = true; } }
测试代码:
加载场景时,记在loading界面,设置需要加载的场景名称;
public class MainScence : MonoBehaviour { public Button btnLoad; void Start() { btnLoad.onClick.AddListener(OnLoadFight); } private void OnLoadFight() { GameObject go = Instantiate(Resources.Load<GameObject>("Loading"), transform); go.GetComponent<Loading>().scenceName = "FightScence"; } }
我是爱玩Unity的少年,有喜欢Unity的各位,欢迎加入Unity行业交流Q群:709851864

浙公网安备 33010602011771号