一、分析需求:
1.需要点击同一按钮来实现操作,说明点击按钮应该是有两种状态,这里需要设置一个bool变量来表示点击当前按钮的时候,所表示的两种状态,在增加还是在减少
2.在规定时间内实现数值的增减,需要知道三个变量,当前的数值,所需要增长到的目标数值以及规定时间,这里的目标数值和规定时间可以不设置变量,但是当前的数值一定要设置并赋初值
3.在增长过程中如果没有增长到最大值就再次点击按钮,则显示当前值,这同时也需要加一个bool变量进行判定是否增加到最大值,如果已经增加到最大值则可以进行减少的操作,如果没有的话,当再次点击按钮的时候就先继续增长到最大值,之后再点击按钮再实现减少的逻辑,反之也成立。
二、代码实现
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class 数值变换 : MonoBehaviour
{
float target = 10f;
float current = 0f;
float time = 4f;
bool isadd = false;
bool attach = false;
Text text;
Button Btn;
void Start ()
{
text = GameObject.Find("Text").GetComponent<Text>();
Btn = GameObject.Find("Button").GetComponent<Button>();
Btn.onClick.AddListener(() =>
{
if (isadd == false)
{
isadd = true;
}
else
{
isadd = false;
}
});
}
void Update ()
{
if (isadd == true)
{
Increase();
}
else
{
Reduce();
}
}
void Increase()
{
current += Time.deltaTime * (target / time);
if (current >= target)
{
current = target;
attach = true;
}
text.text = current.ToString("f2");
}
void Reduce()
{
if (attach == false)
{
if (current < target)
{
}
else
{
current = target;
attach = true;
}
text.text = current.ToString("f2");
}
else
{
current -= target * Time.deltaTime / time;
if (current > 0)
{
}
else
{
current = 0;
attach = false;
}
text.text = current.ToString("f2");
}
}
}
三、效果展示
U3D实现按钮控制数值在规定时间进行变换且中间可停
四、总结补充
上述代码在减少的过程中并没有一个是否到达原数值的一个判定,所以并不能做到点击就显示当前的数值,如果有需求是在减少的过程中也可以随时点,且可以显示当前值的话,可以参考增长的过程进行设置。
若有错误或有更好的解决办法,欢迎在评论区留言;如需转载请标明出处。