Hi, could I ask how I could implement a health bar that decreases gradually instead of setting the fillAmount at once?
Thank you.
Hi, could I ask how I could implement a health bar that decreases gradually instead of setting the fillAmount at once?
Thank you.
I literally just did something like that. I have a health bar that immediately decreases, and then a darker bar that decreases slowly (0.25f speed slowly) after a 0.5f second delay. If more damage happens in that 0.5f seconds it is cancelled until the darker bar has time to start decreasing.
To just decrease (or increase) the bar gradually, you can use a coroutine
[SerializeField] float maxHealth = 100f;
[SerializeField] Image barImage;
[SerializeField] float fillSpeed = 0.25f;
private float currentHealth;
private Coroutine barRoutine;
public void DecreaseHealth(int damageAmount)
{
currentHealth = Mathf.Max(0f, currentHealth - damageAmount);
if (barRoutine != null) StopCoroutine(barRoutine);
barRoutine = StartCoroutine(UpdateBarRoutine());
}
// You could do the same for increasing the health
public void IncreaseHealth(int healAmount)
{
currentHealth = Mathf.Min(maxHealth, currentHealth + healAmount);
if (barRoutine != null) StopCoroutine(barRoutine);
barRoutine = StartCoroutine(UpdateBarRoutine());
}
private IEnumerator UpdateBarRoutine()
{
var requiredPercentage = currentHealth / maxHealth;
while (!Mathf.Approximately(barImage.fillAmount, requiredPercentage))
{
barImage.fillAmount = Mathf.MoveTowards(barImage.fillAmount, requiredPercentage, fillSpeed * Time.deltaTime);
yield return null;
}
barRoutine = null;
}
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.