Converting slider value?

Hi,

I have a health bar that works with the image components “Fill Amount” slider which ranges from 0 to 1. I also have a text mesh pro component with life points that range from 0 to 100.

I want the life points to reflect the fill amount but I dont know how to convert the ranges so that when the fill amount deminishes the life points do as well within the range of 0 to 100. I’ve seen examples that convert ranges but none that do it from one range to another range.

Does anyone know of a simple way to achieve the range conversion I’m looking for?

If you want the image to reflect the percent, you just need to divide current health by max health. Then assign this value to your images fill amount. Note that your health might be an int, so make sure you’re making it a float so that you can get the decimal amount as well. Otherwise, it will not give you the correct value.

Okay, thanks for the advice

So I used the advice of @Brathnann but my situation was the reverse so instead of dividing current and max health I multiplied it by 100. “fillAmount” is the image slider value and I just removed the decimals from visibility. In case anyone else needs this here’s the code

MaxFillAmount = fillAmount * 100;
lifePoints.GetComponent<TextMeshProUGUI>().text = MaxFillAmount.ToString("f0");

For a more generalized conversion, use something like this:

public static float Remap(float value, float oldLow, float oldHigh, float newLow, float newHigh)
{
    return newLow + (value - oldLow) * (newHigh - newLow) / (oldHigh - oldLow);
}
1 Like

You can also create a remap function out of Lerp and InverseLerp:

public static float Remap(float value, float oldLow, float oldHigh, float newLow, float newHigh) {
  float t = Mathf.InverseLerp(oldLow, oldHigh, value);
  return Mathf.Lerp(newLow, newHigh, t);
}

Note that those two lerp functions are clamped. If your “from” range is [10, 50], and your value is 0, the inverse lerp will give you a 0. This may or may not be desirable!

There’s an unclamped version of Lerp, but not an unclamped version of InverseLerp, for whatever reason.

1 Like