在Unity中除了用Slider、Image做进度条,其实用Scrollbar也可以做进度条。
首先,在场景中新建一个Scrollbar组件和一个Text组件:
其次,创建模拟进度的一个脚本,Scrollbar_Progressbar.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class Scrollbar_Progressbar : MonoBehaviour
{
public Scrollbar scrollbar;
public TextMeshProUGUI text;
private float curCount = 0; //当前加载量,从0开始加载
private float allCount = 100f; //总加载量,这里设置为100
private float smoothSpeed = 0.1f; //加载的速度
private bool changeValue;
private bool changeSize;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.A))
{
changeValue = true;
curCount = 0;
scrollbar.size = 0;
}
else if(Input.GetKeyDown(KeyCode.S))
{
changeSize = true;
curCount = 0;
scrollbar.value = 0;
}
if(changeValue)
{
if (curCount < allCount)
{
curCount += smoothSpeed;
if (curCount > allCount)
{
curCount = 100f;
}
scrollbar.value = curCount / 100f;
text.text = (int)curCount / allCount * 100 + "%";
}
else
{
changeValue = false;
}
}
if(changeSize)
{
if (curCount < allCount)
{
curCount += smoothSpeed;
if (curCount > allCount)
{
curCount = 100f;
}
scrollbar.size = curCount / 100f;
text.text = (int)curCount / allCount * 100 + "%";
}
else
{
changeSize = false;
}
}
}
}
我这里特别模拟了改变scrollbar中Value和Size属性的两种情况,经检验,只有改变Size值才符合进度条的效果。
具体效果如下:
Unity 利用UGUI之Scrollbar制作进度条