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

須要三個場景,場景A,場景B,場景C;canvas

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

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

場景C:目標場景;3d

建立OnProgress.cs腳本:code

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場景由兩部分組成,加載進度百分比和進度條:blog

文本就不說了,說明下進度條的實現,進度條實際是一個Image,設置Image Type爲filled,fill Method爲horizonal,這裏必定要添加source Image,不然下面的Image Type不會出來。圖片

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

 

 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場景就不介紹了,就是你要跳轉的目標場景。

相關文章
相關標籤/搜索