就是其他主頁點擊按鈕后先跳轉到這個加載頁面場景, 同時異步加載要跳轉到的場景
參考: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 update
void Start()
{
LoadNextLeaver();//開啟協程(多執行緒?)
}
// Update is called once per frame
void 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 update
void Start()
{
}
// Update is called once per frame
//void Update()
//{
//}
/// <summary>
/// 進度條下方顯示的文本
/// </summary>
[SerializeField]
Text Aegis_text;
/// <summary>
/// 進度條
/// </summary>
[SerializeField]
Slider slider;
/// <summary>
/// 文字后方點數顯示
/// </summary>
float pointCount;
/// <summary>
/// 當前進度
/// </summary>
float progress = 0;
/// <summary>
/// 進度條讀取完成時間
/// </summary>
float total_time = 3f;
/// <summary>
/// 計時器
/// </summary>
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");
}
/// <summary>
/// 文本顯示協程
/// </summary>
/// <returns></returns>
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 += ".";
}
//把顯示內容賦給場景中的text
Aegis_text.text = reminder;
}
}
}
測驗效果

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/289697.html
標籤:其他
