Smooth fill animation change (encreasing, decreasing) in unity

i’m making a UI for my 2d unity game and i’m trying to use Mathf.lerp to make fill of the hearts image represanting player’s health decrease, increase smoothly.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class HealthUIController : MonoBehaviour
    public GameObject heartContainer;
    private float fillValue;

    void Update()
        fillValue = (float)GameController.Health;
        fillValue = fillValue / GameController.MaxHealth;
        heartContainer.GetComponent<Image>().fillAmount = fillValue; // this is where i need to use Mathf.lerp

I’ve read mathf.lerp manual but i still don’t get how it works


You don’t need to use Lerp to have a smoother fill animation, you can do it like this:

Image image;
public float fillSmoothness = 0.01f;

void Start()
    image = heartContainer.GetComponent<Image>();

void Update()
    float prevFill = image.fillAmount;
    float currFill = (float)GameController.Health / GameController.MaxHealth;
    if(currFill > prevFill) prevFill = Mathf.Min(prevFill + fillSmoothness, currFill);
    else if (currFill < prevFill) prevFill = Mathf.Max(prevFill - fillSmoothness, currFill);
    image.fillAmount = prevFill;

In the inspector of the class you can tune fillSmoothness to work as you wish.

Leave a Reply

Your email address will not be published. Required fields are marked *