Enable/Disable Healthbar after a set time

I just wanted to have the health bar behave in such a way that it is only enabled when it is changing and only for a set period of time.

This is the code I have attempted to set that behaviour and I was wondering if there was a better way to approach this outside of coroutines? I used the Fader as an example because it used the same approach there.

using System.Collections;
using UnityEngine;

namespace RPG.Attributes
{
    public class HealthBar : MonoBehaviour
    {
        [SerializeField] Health health = null;
        [SerializeField] RectTransform foreground = null;
        [SerializeField] Canvas rootCanvas = null;
        [SerializeField] float displayTime = 8f;
        
        private void OnEnable()    
        {
              health.onHealthUpdated += UpdateHealthBar;
              health.onNoHealthLeft += DisableHealthBar;
        }

        private void OnDisable()    
        {
              health.onHealthUpdated -= UpdateHealthBar;
              health.onNoHealthLeft -= DisableHealthBar;
        }
   
        private void UpdateHealthBar()
        {   
            // If health is zero/full or is enabled for longer than maxEnableTime, disable health bar
            if (Mathf.Approximately(health.GetFraction(), 0) || Mathf.Approximately(health.GetFraction(), 1)) 
            {
                DisableHealthBar();
                return;
            }

            DisplayHealthBar();
            foreground.localScale = new Vector3(health.GetFraction(), 1.0f, 1.0f);
        }

        private void DisableHealthBar()
        {
              rootCanvas.enabled = false;
        }

        IEnumerator DisplayRoutine()
        {
            rootCanvas.enabled = true;
            yield return new WaitForSeconds(displayTime);
            rootCanvas.enabled = false;
        }

        Coroutine DisplayHealthBar()
        {
            return StartCoroutine(DisplayRoutine());
        }
    }
}

Basically after 8 seconds since it is enabled when the health bar is updated, it is disabled again.

Looks fine to me. It’s the way I would’ve done it, too. You could have used Invoke

private void DisplayHealthBar()
{
    rootCanvas.enabled = true;
    Invoke(nameof(DisableHealthBar), displayTime);
}

But it just creates a coroutine under the hood anyway

1 Like

@bixarrio’s answer is pretty much identical to my own answer.

1 Like

Privacy & Terms