Unity模擬資源加載界面

首先在場景中新建一個Image並把圖片的填充模式改爲Filled(在這裏用LoadingFill代替),並新建一個Text文本用於顯示當前進度加載的進度值(在這裏我用Num代替)。然後新建一個父物體(在這裏我用LoadingBG代替),並把新建的Image和Text作爲父物體中的子物體存在。再新建一個腳本Login,並把這個腳本掛載到LoadingBG上面!!!
打開腳本,並複製以下的代碼:
在這裏插入圖片描述

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;

public class Login : MonoBehaviour {

    private Transform m_Trasform;
    private Image bg_LoadingBg_LoadingFill;
    private Text bg_LoadingBg_Num;

    private float value;

    void Awake()
    {
        m_Trasform = gameObject.GetComponent<Transform>();
        bg_LoadingBg_LoadingFill = m_Trasform.Find("LoadingFill").GetComponent<Image>();
        bg_LoadingBg_Num = m_Trasform.Find("Num").GetComponent<Text>();
        bg_LoadingBg_LoadingFill.fillAmount = 0;
        StartCoroutine(Loading());
    }

    IEnumerator Loading()
    {
        while (value < 0.95f)
        {
            value += UnityEngine.Random.Range(0.01f, 0.1f);
            //採用Math.Round四捨五入方法保留兩位小數,然後在乘於100就等於當前進度加載的百分比
            bg_LoadingBg_Num.text = Math.Round(value, 2) * 100 + "%";
            Debug.Log(bg_LoadingBg_Num.text);
            bg_LoadingBg_LoadingFill.fillAmount = value;
            //每次加載後就等待0.2秒後就繼續加載
            yield return new WaitForSeconds(0.2f);
        }
        bg_LoadingBg_LoadingFill.fillAmount = 1;
        bg_LoadingBg_Num.text = "100%";
        Debug.Log("資源記載完畢!!!");
    }
}

然後就可以運行遊戲測試效果!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章