unity 之 場景切換進度條顯示


一、UI。建立slider適當更改即可;

 

 

 

二、新增loadScene腳本,用來進行場景切換,將其綁定任意物體上面。博主以放置主相機為例。參數分別為進度條(用來設置value值),顯示進度文本text

 

在設置中加入兩個場景:

 

三、腳本;

 1 /// <summary>
 2 /// 場景切換
 3 /// 在unity 獲取當前加載進度progress中,其中最多到0.9.只有等到加載到第二個場景才會到1
 4 /// 所有在加載進度條時如果progress的值近似0.9,則直接將進度參數設置為1,實現進度到100%
 5 /// 並且progress的值是在一幀加載一些資源,所以其值不會是連續的,因此設置兩個參數來記錄當前
 6 /// 進度和頁面顯示的進度,進行++。
 7 /// </summary>
 8 public class loadScene : MonoBehaviour
 9 {
10     AsyncOperation async;
11     public Slider slider;
12     public Text text;//百分制顯示進度加載情況
13 
14     void Start()
15     {
16         //開啟協程
17         StartCoroutine("loginMy");
18     }
19     
20     void Update()
21     {
22        
23     }
24     IEnumerator loginMy()
25     {
26         int displayProgress = 0;
27         int toProgress = 0;
28         AsyncOperation op = SceneManager.LoadSceneAsync(1);
29         op.allowSceneActivation = false;
30         while (op.progress < 0.9f)  //此處如果是 <= 0.9f 則會出現死循環所以必須小0.9
31         {
32             toProgress = (int)op.progress * 100;
33             while (displayProgress < toProgress)
34             {
35                 ++displayProgress;
36                 SetLoadingPercentage(displayProgress);
37                 yield return new WaitForEndOfFrame();//ui渲染完成之后
38             }
39         }
40         toProgress = 100;
41         while (displayProgress < toProgress)
42         {
43             ++displayProgress;
44             SetLoadingPercentage(displayProgress);
45             yield return new WaitForEndOfFrame();
46         }
47         op.allowSceneActivation = true;
48 
49     }
50 
51     private void SetLoadingPercentage(int displayProgress)
52     {
53         slider.value = displayProgress;
54         text.text = displayProgress.ToString() + "%";
55     }
56 }

四、運行:

   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM