Eager to see how you enable/disable your Health Bar

this.gameObject.SetActive(!healthComponent.IsDead());

The above line is all I used to enable/disable my healthBars.

Is that called in Update()?
I was thinking of having the health bar start off disabled and then placing a call similar to yours in TakeDamage() so that once enemies are hit for the first time, the HP bar pops up.

yes called in Update before updating the healthBar.

I used a slider instead… I destroy it if enemy is dead

using RPG.Resources;
using RPG.Stats;
using UnityEngine;
using UnityEngine.UI;

namespace RPG.UI.EnemyHealthBar
{
    public class EnemyHealthBar : MonoBehaviour
    {
        [SerializeField] Slider enemyHealthSlider;
        [SerializeField] GameObject enemyMain;
        Health healthScript;
        BaseStats baseStatsScript;

        private void Start()
        {
            baseStatsScript = enemyMain.GetComponent<BaseStats>();
            healthScript = enemyMain.GetComponent<Health>();
            SetEnemySliderMaximumValue();
        }


        void Update()
        {
            if (healthScript.IsDead())
            {
                Destroy(gameObject);
            }
            SetEnemySliderValue();
        }

        private void SetEnemySliderMaximumValue()
        {
            enemyHealthSlider.maxValue = baseStatsScript.GetStat(Stat.Health);
        }

        private void SetEnemySliderValue()
        {
            enemyHealthSlider.value = healthScript.GetHealthPoints();
        }
    }
}

I personally don’t like to use sliders if the player is not going to manually move it, I find the process way too convoluted: remove all the interactive features, remove all the unwanted child objects which are a lot, use an specific namespace (I don’t know why I like avoiding using Unity.UI, everything feels… cleaner, for some weird reasons, probably I’m just crazy, no, not probably, I’m crazy), access the slider value in a very specific way… and blablabla

And that’s why always end up over complicating everything. “I don’t like Unity’s sliders! I’m going make my own for no reason whatsoever!” Don’t be like me kids, use everything you have to make your job easier.

1 Like

Both methods have their merits.

I fill the Same way about sliders. I do however typically when git to the polishing phase update my images (i.e. I have an image for the background and an ime that fits in the Backround for the bar.) when I update to this instead of setting the scale of the Foreground Image, I set the fill amount of the Image.

private void SetImageFill()
{
    if (_hasImage) statValueImage.fillAmount = GetFillPercentage();
}

private float GetFillPercentage()
{
    return _max > 0.01f ? _value / _max : 0;
}

I find this more convenient as it allows me to change the way it fills and not have to change any code. I can have Vertical Bars, Horizontal Bars, Globes, Heart Containers. They all use the same code.


1 Like

Privacy & Terms