-
::tristanshaw7255 from Part 5’s YouTube comments writes:
I changed the healing to check for the difference between max and current health first, rather than lowering the currenthp to max if it exceeds, so avoid any issues.
public void RestoreHealth(float amount)
{
if (currentHealth < characterData.MaxHealth)
{
// if the amount healed would exceed max health, heal to full instead
if (amount > (characterData.MaxHealth - currentHealth))
{
currentHealth = characterData.MaxHealth;
}
// otherwise, just gain the health
else
{
currentHealth += amount;
}
}
}
::Here’s another more concise solution. We can use Mathf.Min()
to always automatically cap the health to the max health value:
public void RestoreHealth(float amount) {
currentHealth = Mathf.Min(currentHealth + amount, characterData.MaxHealth);
}
This works because Mathf.Min()
always picks the smaller value, so if your character’s health exceeds the max health, then the max health value will be used instead.