- Home /
Question by
henrywoodaqp · Feb 23, 2021 at 11:06 PM ·
lerpslider
How to lerp health slider
I'm making a health bar, from the Brackey's tutorial, I've tried lerp a million different ways and nothing, it moves at fractions, speed doesn't change anything and I'm stumped, would appreciate some help:
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
public Slider healthSlider;
public void SetMaxHealth(float health)
{
healthSlider.maxValue = health;
healthSlider.value = health;
}
public void SetHealth(float health)
{
healthSlider.value = health;
}
}
Comment
Best Answer
Answer by highpockets · Feb 24, 2021 at 01:17 AM
Well, you haven’t implemented any kind of a lerping function in there at all and you will likely want that to happen in the SetHealth function.
private float targetHealth;
private float timeScale = 0;
private bool lerpingHealth = false;
public void SetHealth( float health )
{
targetHealth = health;
timeScale = 0;
if(!lerpingHealth)
StartCoroutine(LerpHealth());
}
private IEnumerator LerpHealth( )
{
float speed = 2;
float startHealth = healthSlider.value;
lerpingHealth = true;
while(timeScale < 1)
{
timeScale += Time.deltaTime * speed;
healthSlider.value = Mathf.Lerp(startHealth, targetHealth, timeScale);
}
lerpingHealth = false;
}
You will of course need the System.Collections using directive for the IEnumerator
Thank you very much, I had a devil of a time trying out lerp but for some reason it never seemed to work, either way youve helped out tremendously. Once again thanks, cheers