Unity3D之UGUI——製作非同步載入場景進度條
阿新 • • 發佈:2018-11-27
製作遊戲經常要實現兩個場景的切換,但由於載入場景需要一定時間,所以為了優化玩家體驗,在第一個場景中製作一個進度條顯示載入進度。 現在就在unity中實現,go go!
開啟unity,新建場景 GameMainUI,製作一個開始遊戲的介面如下圖。
play與exit都為按鈕,在text上加Button元件即可製作。
現在製作進度條,在canvas下建立Panel改為LoadingPanel,在LoadingPanel下建立image改為loadingbg作為進度條的載入背景圖,調為紅色。
在loadingbg下新增image元件progress 作為滑動進度條,新增text元件proText作為顯示載入完成百分比。
image元件progress,image Type:Filled , Fill Method : Horizontal
顏色自定,與背景圖區分,現在拖動Fill Amount就可以看到效果
text元件proText效果如下:
介面完成,現在是程式碼部分:
建立C#指令碼 MyMenuUI.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class MyMenuUI : MonoBehaviour { //新遊戲按鈕 public Button newGameButton; //退出按鈕 public Button exitButton; //載入介面 public GameObject loadPanel; //滑動進度條 public Image progressImg; //進度顯示百分比 public Text proText; //非同步載入程序 private AsyncOperation async; //不斷更新的進度值 private int curProgressValue = 0; void Start() { loadPanel.SetActive(false);//一開始禁用載入層。 } /// <summary> /// Play按鈕點選事件 /// </summary> public void NewGamePressed() { StartCoroutine(LoadScene());//呼叫載入場景的協程 loadPanel.SetActive(true);//啟用載入介面 } /// <summary> /// 載入場景協程 /// </summary> /// <returns></returns> IEnumerator LoadScene() { async = SceneManager.LoadSceneAsync("TankGameScene"); async.allowSceneActivation = false;//此處將允許自動場景載入禁用,防止到90%時自動跳轉到新場景。 yield return async; } void Update() { if (async == null) { return;//程序為空,跳出該函式 } //總的進度值 int progressValue = 100; if (curProgressValue < progressValue) { curProgressValue++; } proText.text = "Loading "+curProgressValue + "%";//實時更新進度百分比的文字顯示 progressImg.fillAmount = curProgressValue / 100f;//實時更新滑動進度圖片的fillAmount值 if (curProgressValue == 100) { async.allowSceneActivation = true;//啟用自動載入場景 proText.text = "OK";//文字顯示完成OK } } /// <summary> /// EXIT按鈕點選事件 /// </summary> public void ExitGamePressed() { //退出整個遊戲 Application.Quit(); } }
將MyMenuUI.cs掛在到MainCamera上,並繫結相關元件
現在執行可能會出問題,可能是第二場景沒新增到Scence in build,我的是新建了名為 TankGameScene 的場景,你可以自己製作要載入的第二個場景,儲存好。
開啟File---->Build Setting
點選Add Open Scences 確保切換載入的兩個場景都被載入
現在到第一場景,點選執行後,點選Play按鈕,就能看到效果!
nice nice!
這是我的第一篇博文,有幸被你看到,第一個留言的訪客,寫下你的QQ,發個小紅包給你,哈哈 !
如果有問題歡迎提出,互相交流學習!Go GO!繼續成長之路。
工程下載地址:連結:http://pan.baidu.com/s/1pLyrL2N 密碼:2lq8