Unity 利用UGUI之Slider制作进度条

Unity中使用Slider和Text组件可以制作简单的进度条。

首先在场景中右键->UI->Slider,新建一个Slider组件:

同样方法新建一个Text组件,最终如图:

创建一个进度模拟脚本,Slider_Progressbar.cs

using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
​
public class Slider_Progressbar : MonoBehaviour
{
    public Slider slider;
    public TextMeshProUGUI text;
​
    private float curCount = 0;  //当前加载量,从0开始加载
    private float allCount = 100f;   //总加载量,这里设置为100
​
    private float smoothSpeed = 0.1f;  //加载的速度
​
    // Start is called before the first frame update
    void Start()
    {
​
    }
​
    // Update is called once per frame
    void Update()
    {
        if (curCount < allCount)
        {
            curCount += smoothSpeed;
            if (curCount > allCount)
            {
                curCount = 100f;
            }
            slider.value = curCount / 100f;
            text.text = (int)curCount / allCount * 100 + "%";
        }
    }
}
​

把该脚本拉到场景中,并把Slider和Text组件拉到脚本中的slider和text变量中:

运行场景,大功告成!

Unity 利用UGUI之Slider制作进度条

猜你喜欢

转载自blog.csdn.net/mr_five55/article/details/135466710