Delayed Removal of Health Bar to show Health going to 0 first

I love all the ideas people are generating here. I wanted to add my own. This uses events to update health bar and has separate events for health changes and characters getting killed.

It was great practice of integrating knowledge from several lectures and also allowed me to create some effects. I thought of using EventArgs too to pass the Health component in the event but since I had already connected the Health component I ended up not changing it.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace RPG.Attributes
{
    public class HealthBar : MonoBehaviour
    {
        [SerializeField] private Health healthComponent = null;
        [SerializeField] private Image remainingHealthImage;
        [SerializeField] private Canvas rootCanvas = null;
        [SerializeField] private float disableHealthBarDelay = 0.2f;

        private void OnEnable()
        {
            healthComponent.HealthChanged += HealthComponent_HealthChanged;
            healthComponent.CharacterDied += HealthComponent_CharacterDied;
        }

         private void OnDisable()
        {
            healthComponent.HealthChanged -= HealthComponent_HealthChanged;
            healthComponent.CharacterDied -= HealthComponent_CharacterDied;
        }

        private void HealthComponent_HealthChanged()
        {
            remainingHealthImage.fillAmount = healthComponent.GetHealthNormalized();
        }

        private void HealthComponent_CharacterDied()
        {
            StartCoroutine(DisableCanvasAfterSeconds(disableHealthBarDelay));
        }

        private IEnumerator DisableCanvasAfterSeconds(float delay)
        {
            yield return new WaitForSeconds(delay);
            rootCanvas.enabled = false;
        }
    }
}
1 Like

Good job!

I would’ve disabled the canvas in a similar way, but that’s because I keep forgetting there’s an Invoke method.

private void DisableCanvas() => rootCanvas.enabled = false;

private void HealthComponent_CharacterDied() => Invoke(nameof(DisableCanvas), disableHealthBarDelay);
1 Like

Privacy & Terms