Unity模拟资源加载界面

首先在场景中新建一个Image并把图片的填充模式改为Filled(在这里用LoadingFill代替),并新建一个Text文本用于显示当前进度加载的进度值(在这里我用Num代替)。然后新建一个父物体(在这里我用LoadingBG代替),并把新建的Image和Text作为父物体中的子物体存在。再新建一个脚本Login,并把这个脚本挂载到LoadingBG上面!!!
打开脚本,并复制以下的代码:
Unity模拟资源加载界面_第1张图片

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("资源记载完毕!!!");
    }
}

然后就可以运行游戏测试效果!!!

你可能感兴趣的:(Unity)