In the game development process, we will inevitably encounter making progress bar. Here I created from scratch to be a simplified version of the scene.
1, ready to work.
Create a simple UI interface in Unity.
Like this:
which imgBG and imgFillAmount size to be the same.
:( imgFillAmount modify the properties of the Image Type changed Filled, remember to join the Sprite in the Source Image)
See FillAmount attribute is a value from 0 to 1, you can see the effect of the drag.
Finally, create a Test script to mount on imgFillAmount preparatory work is done.
2, the idea: obtain all the values 0 to 1 in FillAmount Mathf.Lerp method used within a specified time.
①, here I would like to explain my understanding of the Mathf.Lerp. for example:
Mathf.Lerp(0, 1, 0.5f);
0.5 sentence is obtained in this value between 0 and 1, i.e. this line of code is obtained 0.5.
②, then I will simply describe the small timer to code as an example:
//初始时间
float timer = 0;
//预设一个时间
float duration = 1;
void Timer()
{
//通过Time.deltaTime方法获取到每帧的时间间隔,然后累加起来得到一个从0开始计时的时间
timer += Time.deltaTime;
//判断累加的时间有没有到达我们所预设的时间
if (timer >= duration)
{
Debug.Log("TimeOut");
}
}
Note: Be sure to write in the Update.
3, to achieve the effect: Click the mouse button to start to read the article, read over the end.
using UnityEngine;
using UnityEngine.UI;
public class test : MonoBehaviour
{
//声明imgFillAmount
private Image imgFillAmount;
//是否开始读条
bool isPlay = false;
//计时用:初始时间
float timer = 0;
//计时用:读条所用的全部时间
float duration = 1;
void Start()
{
//获取到刚刚修改Image Type为Filled的Image
imgFillAmount = GetComponent<Image>();
}
void Update()
{
//判断是否开始读条
if (isPlay)
{
//使timer根据时间增长
timer += Time.deltaTime;
//修改FillAmount的值
//(使当前时间占全部时间的比例为FillAmount中0到1之间的值)
imgFillAmount.fillAmount = Mathf.Lerp(0, 1, timer / duration);
//计时器
if (timer >= duration)
{
//停止读条
isPlay = false;
//将timer还原为0,为下一次计时做准备
timer = 0;
}
}
//鼠标点击
if (Input.GetMouseButtonDown(0))
{
//开始读条
isPlay = true;
}
}
}
This completes a simple progress bar effects.