So, I have a image that starts off with a fill of 0. Then once a Boolean is true, it runs some code that fills the image to a specific amount. My problem is that I am adding a condition to check if the fill amount is met, but the fill amount goes beyond the max amount.
private void Update() {
if (update) {
if (icon.fillAmount < icon.fillAmount + amount) {
icon.fillAmount += amount * Time.deltaTime;
Debug.Log(icon.fillAmount);
} else update = false;
}
}
In my code, I have an update boolean, and when it is true, it checks if the fill amount less than the maximum fill amount. If that is false, then it runs a line of code to increment the fill amount smoothly, then it logs the fill amount, otherwise it changes the update boolean to false. But, for example if amount = 0.5f
, when I log the fillAmount
, it does over amount
. I think it has to do with the Time.deltaTime
, but I do not know how to solve it.
Use Mathf.MoveTowards
to achieve what you want. According to Unity3D documentation this function:
Moves a value current towards target.
This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta . Negative values of maxDelta pushes the value away from target.
if (update) {
if (icon.fillAmount < 1) {
icon.fillAmount = Mathf.MoveTowards(icon.fillAmount, 1, amount * Time.deltaTime);
Debug.Log(icon.fillAmount);
} else update = false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.