Search code examples
c#unity-game-enginefilllerp

Unity fill amount lerp


Trying to lerp image fill amount from this script.

public class ProgressBar : MonoBehaviour
{
    public static int minimum;
    public static int maximum;
    public static int current;
    public Image mask;


    void Update()
    {
        GetCurrentFill();
    }

    void GetCurrentFill()
    {
        float currentOffset = current - minimum;
        float maximumOffset = maximum - minimum;
        float fillAmount = currentOffset / maximumOffset;
        mask.fillAmount = fillAmount;
    }
}

i'm going to explain this code :

Current = current value, minimum = minimum experience to level up, maximum = maximum experience to level up

   if(skortotal < 20)
        {
            playerlevel = 1;
            ProgressBar.minimum = 0;
            ProgressBar.current = skortotal;
            ProgressBar.maximum = 20;
        }
        if(skortotal >= 20)
        {
            playerlevel = 2;
            ProgressBar.current = skortotal;
            ProgressBar.maximum = 50;
            ProgressBar.minimum = 20;
        }
}

the code already work but i don't know how to make it work using lerp


Solution

  • You asked how to achieve this using Mathf.Lerp, here is my suggestion:

    mask.fillAmount = Mathf.Lerp(minimum, maximum, current) / maximum;
    

    Lerp will automatically clamp the values, so the result is always inside of [0..1].

    To animate the fill over time you can try this:

    float actualValue = 0f; // the goal
    float startValue = 0f; // animation start value
    float displayValue = 0f; // value during animation
    float timer = 0f;
    
    // animate the value from startValue to actualValue using displayValue over time using timer. (needs to be called every frame in Update())
    timer += Time.deltaTime;
    displayValue = Mathf.Lerp(startValue, actualValue, timer);
    mask.fillAmount = displayValue;
        
    

    To start the animation, do this when you change the actualValue:

    actualValue = * some new value *;
    startValue = maskFillAmount; // remember amount at animation start
    timer = 0f; // reset timer.