Skip to content

Optimize Health Bar

Aprius edited this page Oct 23, 2024 · 9 revisions

What

Optimized health bar rendering with a single draw command, useful for Roguelike games where there are many units on screen at the same time, and does not require too much customization in terms of healthbar display

It will draw the entire health bar with just 1 draw call

image

Setup

1, Create Canvas and set render mode is Screen Space - Overlay

image

2, Create a GameObject in the newly created canvas then add component UIHeathBarManager

image

  • Camera : Camera render canvas contains healthBars
  • Height : Adjust the height of the health bar
  • Border : Adjust the thickness of the border surrounding the health bar
  • Background : Adjust the background color of the health bar

Note that you need to set the pivot of the **UIHeathBarManager ** to the origin (0, 0)

image

3, Attach the HeathBar component to the object that needs to display the health bar.

image

  • Width : Length of the health bar
  • Opacity : Adjust the opacity, 0 is equivalent to 100% opacity and 1 is equivalent to 0% opacity at this point you will not see the health bar
  • Color : Color of the health bar
  • Offset : Adjust the position offset

4, Setup the value for the health bar by calling the Initialize function of HealthBar

    public void Initialize(float maxHp, Action<float, bool> onHpChangeEvent, Action onDeadEvent)
    [SerializeField] private HealthBar healthBar;

    private void Start()
    {
        healthBar.Initialize(100, OnHPChangedValue, OnDeath);
    }


    /// <summary>
    /// The second parameter indicates whether the blood volume is increased when true and decreased when false.
    /// </summary>
    private void OnHPChangedValue(float currentHp, bool isRecovery)
    {
        // TODO
    }


    private void OnDeath()
    {
        // TODO
    }

5, Use the TakeDamage function directly to change the value of the health bar or use TakeDamage through DamageHelper to change the value using the Strategy pattern

healthBar.TakeDamage(10);
Clone this wiki locally