素材巴巴 > 程序开发 >

Unity_加载页面及进度条

程序开发 2023-09-11 22:05:50

就是其他主页点击按钮后先跳转到这个加载页面场景, 同时异步加载要跳转到的场景

参考:Unity SceneManager场景管理Chinar详解API

Unity 场景异步加载(加载界面的实现)


新建一个加载页面场景

创建一个滑动条用来表示进度条

 

再创建一个文本用来显示进度百分比

 位置随便摆一下

创建一个空对象

在空对象上新建挂载脚本

 

修改代码:

/*加载场景页面*/
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;using UnityEngine.UI;
 using UnityEngine.SceneManagement;//场景管理public class Load_test : MonoBehaviour
 {// Start is called before the first frame updatevoid Start(){LoadNextLeaver();//开启协程(多线程?)}// Update is called once per framevoid Update(){}public GameObject image;   //加载界面public Slider slider;   //进度条public Text text;      //加载进度文本public void LoadNextLeaver(){image.SetActive(true);StartCoroutine(LoadLeaver());}IEnumerator LoadLeaver(){AsyncOperation operation = SceneManager.LoadSceneAsync(2); //准备加载序号为2的场景operation.allowSceneActivation = true;//加载完成后,是否允许场景跳转while (!operation.isDone)   //当场景没有加载完毕{slider.value = operation.progress;  //进度条与场景加载进度对应text.text = (operation.progress * 100).ToString() + "%";yield return null;}}
 }

 运行测试,可以实现跳转和进度条


但目标场景太小了,瞬间闪一下就加载完了,就很出戏 

一个伪加载实现:

参考:Unity协程实现伪加载页面

using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;using UnityEngine.UI;public class Load_test_ : MonoBehaviour
 {// Start is called before the first frame updatevoid Start(){}// Update is called once per frame//void Update()//{//}/// /// 进度条下方显示的文本/// [SerializeField]Text Aegis_text;/// /// 进度条/// [SerializeField]Slider slider;/// /// 文字后方点数显示/// float pointCount;/// /// 当前进度/// float progress = 0;/// /// 进度条读取完成时间/// float total_time = 3f;/// /// 计时器/// float time = 0;void OnEnable(){//开启协程StartCoroutine("AegisAnimation");}void Update(){//记录时间增量time += Time.deltaTime;//当前进度随着时间改变的百分比progress = time / total_time;if (progress >= 1){UnityEngine.SceneManagement.SceneManager.LoadScene(2);//假装的加载完成后,还是要跳转到目标场景return;}//把进度赋给进度条的值slider.value = progress;}void OnDisable(){//关闭协程StopCoroutine("AegisAnimation");}/// /// 文本显示协程/// /// IEnumerator AegisAnimation(){while (true){yield return new WaitForSeconds(0.1f);float f = slider.value;//设置进度条的value值在某个区间的时候要显示的字符串string reminder = "";if (f < 0.25f){reminder = "检测余额中...";}else if (f < 0.5f){reminder = "注入木马中...";}else if (f < 0.75f){reminder = "破解密码中...";}else{reminder = "上传数据中...";}//显示字符串后面的“.”pointCount++;if (pointCount == 7){pointCount = 0;}for (int i = 0; i < pointCount; i++){reminder += ".";}//把显示内容赋给场景中的textAegis_text.text = reminder;}}
 }
 

测试效果


标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。