Forum begins after the advertisement:


[Part 5] Alternative way to code max health cap when healing

Home Forums Video Game Tutorial Series Creating a Rogue-like Shoot-em Up in Unity [Part 5] Alternative way to code max health cap when healing

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #11918
    Terence
    Level 30
    Keymaster
    Helpful?
    Up
    0
    ::

    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;
            }
        }
    }
    #11919
    Terence
    Level 30
    Keymaster
    Helpful?
    Up
    0
    ::

    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.

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: