- Home /
Unity Health Slider Lerp in Exact seconds.
I used a slider as a health bar. Values go from 0 to max health of the player. Now when the player takes damage I want to decrease the slider value to new health value but I want slider to finish moving in a certain second.
For example: If the player takes 20 damage, the slider value decrease in 3 seconds. If the player takes 80 damage, again slider value decrease in 3 seconds.
All the examples of sliders I could find were the exact opposite of what I want, bigger the gap between values it take longer to finish but I don't want this.
Answer by Casiell · Apr 13, 2020 at 12:38 PM
int totalTime = 3; //animation time in seconds
private IEnumerable ReduceSlider(float value)
{
var startValue = slider.currentValue;
var endValue = startValue - value;
float lerp = 0;
while(lerp < 1)
{
lerp += Time.deltaTime / totalTime;
slider.currentValue = Mathf.Lerp(startValue, endValue, lerp);
}
slider.currentValue = endValue; //adding Time.deltaTime will probably never add to a full number, this is just rounding the slider value so it's exactly what we want
}
You didn't share your code so I have to come up with my own method to reduce slider value over time.
To increase slider value just change the endValue to startValue + value
Your answer
![](https://koobas.hobune.stream/wayback/20220612231307im_/https://answers.unity.com/themes/thub/images/avi.jpg)