public class TextValueChange : MonoBehaviour
{
[SerializeField]
private Text text;
[SerializeField]
private float time = 0;//改变的总时间
[SerializeField]
private long count = 0;//改变总次数
private bool isStart = false;
private long endValue;//最终筹码
private long currentValue;//当前筹码
private long step;//改变的步长
private float perTime;//多久变动一次
private long changeCount;//当前改变的次数
private bool isAdd = true;//是否增加
public System.Action FinishChangeEvent;
private void Start()
{
StartChange(1000, 100);
}
// Update is called once per frame
void Update()
{
if (isStart)
{
if (perTime >= time / count)
{
perTime = 0;
changeCount++;
//增加
if (isAdd)
{
currentValue += step;
//大于等于目标,结束改变
if (currentValue >= endValue)
{
currentValue = endValue;
isStart = false;
Finish();
changeCount = 0;
}
}
else
{
currentValue -= step;
//小于等于目标,结束改变
if (currentValue <= endValue)
{
currentValue = endValue;
isStart = false;
Finish();
changeCount = 0;
}
}
//改变次数达到总次数,结束改变
if (changeCount >= count)
{
currentValue = endValue;
isStart = false;
Finish();
changeCount = 0;
}
SetTextValue(currentValue);
}
else
{
perTime += Time.deltaTime;
}
}
}
private void SetTextValue(long value)
{
text.text = value.ToString();
}
//设置最终值
public void SetEndValue(long value)
{
endValue = value;
}
//设置起始和结束值,start>end增加,start>end减小
public void StartChange(long start, long end)
{
//获取当前值
currentValue = start;
endValue = end;
long valueLen = 0;//改变的差值
if (currentValue > endValue)
{
valueLen = currentValue - endValue;
isAdd = false;
}
else if (currentValue < endValue)
{
valueLen = endValue - currentValue;
isAdd = true;
}
else
{
SetTextValue(end);
}
long temp;
if (count <= changeCount)
{
temp = valueLen;
}
else
{
temp = valueLen / (count - changeCount);
}
if (temp == 0)
{
temp = 1;
}
step = temp;
isStart = true;
}
public bool GetState()
{
return isStart;
}
void Finish()
{
FinishChangeEvent?.Invoke();
}
private void OnDestroy()
{
FinishChangeEvent = null;
}
}
把脚本挂到组件上,设置改变时间和次数,调用StartChange方法,设置起始值和结束值。