Make the health bar fill smoothly over time
I want to make my health bar gradually fill (not the chunk of the bar corresponding to the recovered health just increasing the bar in an instant) as the health is regenerated, currently, a base player has 1 health per second of regeneration, so I would like to make the bar increase the portion corresponding to 1 point of health (or the current health regen) over a second.
That's the code I have right now to fill the bar:
public class UIHealthBar : MonoBehaviour {
public PlayerStats stats;
public RectTransform healthBarArea;
public RectTransform healthBarFill;
public Text healthBarValues;
void Update () {
float healthPercent = Mathf.Clamp((float)stats.health.StatCurrentValue / (float)stats.health.StatBaseValue, 0f, 1f);
float newRightOffset = -healthBarArea.rect.width + healthBarArea.rect.width * healthPercent;
healthBarFill.offsetMax = new Vector2 (newRightOffset, healthBarFill.offsetMax.y);
healthBarValues.text = string.Format("{0} / {1}",
stats.health.StatCurrentValue,
stats.health.StatBaseValue);
}
}
I have thought and tried a lot of things, but I can't make it work as I want, what would you recommend?
Comment
healthBarFill.offset$$anonymous$$ax = new Vector2($$anonymous$$athf.Lerp(healthBarArea.offset$$anonymous$$ax.x, newRightOffset, Time.time), healthBarFill.offset$$anonymous$$ax.y);
Tried to lerp between the current x offset and the new one, but does not work, what am I doing wrong?
Your answer
![](https://koobas.hobune.stream/wayback/20220612035452im_/https://answers.unity.com/themes/thub/images/avi.jpg)