Unity場景載入與進度條
阿新 • • 發佈:2019-01-01
因為專案的一個場景比較大,在載入的時候有明顯的等待,所以決定做個進度條。
講道理做了多媒體之後已經很久沒有在一個專案裡用到多個場景了,上一次用的時候還是application.loadlevel,現在已經改成了SceneManager。
直接載入場景
1.using UnityEngine.SceneManagement;
2.SceneManager.LoadScene(index/scenename)
做場景載入要確保場景已經被新增進了build setting的scenes in build中
加個進度條
首先將SceneManager.LoadScene換成SceneManager.LoadSceneAsync,它返回一個AsyncOperation型別的返回值,這個返回值包括了progress,isdone屬性,還可以設定是否場景載入完就跳轉(有的遊戲是場景載入完需要按一個按鈕才進入場景,有的是直接進入)
然後需要根據AsyncOperation的progress修改ui的值,實現進度條
進度條在其實就是講一張圖片的image type設定為filled,然後選擇水平,然後修改它的fill amount
我看到網上有一篇部落格介紹瞭如何讓進度條更平滑,感覺還不錯,只是貼程式碼的時候估計沒有測試,資料型別轉換都不對,導致一直死迴圈。
程式碼如下
IEnumerator startLoad(string sceneName) { int displayProgress = 0; int targetProgress = 0; AsyncOperation ao = SceneManager.LoadSceneAsync(sceneName, LoadSceneMode.Single); ao.allowSceneActivation = false; while (ao.progress < 0.9f) { Debug.Log(ao.progress); targetProgress = (int)(ao.progress * 100); while (displayProgress < targetProgress) { displayProgress++; //Debug.Log(displayProgress); percentText.text = displayProgress + "%"; loadBar.fillAmount = (float)displayProgress / 100; yield return new WaitForEndOfFrame(); } //yield return new WaitForEndOfFrame(); } //Debug.Log(targetProgress); targetProgress = 100; while (displayProgress < targetProgress) { displayProgress++; //Debug.Log(displayProgress); percentText.text = displayProgress + "%"; loadBar.fillAmount = (float)displayProgress / 100; yield return new WaitForEndOfFrame(); } ao.allowSceneActivation = true; }
補充,我使用幾個cube測試場景跳轉的時候發現光線變黑了,這個問題很久前就聽別人說過但因為自己一直用不上場景跳轉沒有就沒注意,今天順勢百度了一下
選擇選單window-》lighting 取消auto generate,點選generate lighting。不明覺厲