Unity3D 場景切換加載進度條實現


需要三個場景,場景A,場景B,場景C;

場景A:一個按鈕,點擊加載場景B;

場景B:從A切換到C過度場景,加載進度條;

場景C:目標場景;

創建OnProgress.cs腳本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class OnProgress : MonoBehaviour {

    public void OnBtnClick()
    {
        Debug.Log("clicked");
        Globe.nextSceneName = "MainScene";//目標場景名稱
        SceneManager.LoadScene("Loading");//加載進度條場景
    }
}

創建一個panel,在panel下創建一個button,將OnProgress腳本掛載到canvas,點擊button,設置button屬性,綁定腳本方法,點擊加號,選擇canvas中剛才綁定腳本中的方法OnBtnClick。至此,A場景完成。

創建B場景Loading:

Loading場景由兩部分組成,加載進度百分比和進度條:

文本就不說了,說明下進度條的實現,進度條實際是一個Image,設置Image Type為filled,fill Method為horizonal,這里一定要添加source Image,否則下面的Image Type不會出來。

另外說下添加圖片,普通的圖片添加到assets中不能直接添加到Source Image中,需要對圖片進行設置,如下圖:

 

 OK,再看進度條加載過程的實現:

創建AsyncLoadScene腳本:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class Globe
{
    public static string nextSceneName;
}

public class AsyncLoadScene : MonoBehaviour
{
    public Text loadingText;
    public Image progressBar;

    private int curProgressValue = 0;

    private AsyncOperation operation;

    // Use this for initialization
    void Start()
    {
        if (SceneManager.GetActiveScene().name == "Loading")
        {
            //啟動協程
            StartCoroutine(AsyncLoading());
        }
    }

    IEnumerator AsyncLoading()
    {
        operation = SceneManager.LoadSceneAsync(Globe.nextSceneName);
        //阻止當加載完成自動切換
        operation.allowSceneActivation = false;

        yield return operation;
    }

    // Update is called once per frame
    void Update()
    {

        int progressValue = 100;

        if (curProgressValue < progressValue)
        {
            curProgressValue++;
        }

        loadingText.text = curProgressValue + "%";//實時更新進度百分比的文本顯示  

        progressBar.fillAmount = curProgressValue / 100f;//實時更新滑動進度圖片的fillAmount值  

        if (curProgressValue == 100)
        {
            operation.allowSceneActivation = true;//啟用自動加載場景  
            loadingText.text = "OK";//文本顯示完成OK  

        }
    }
}

將腳本掛在到Loading場景的camera上面。設置對象:

這樣進度條加載場景就完成了,C場景就不介紹了,就是你要跳轉的目標場景。


免責聲明!

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



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