Passing Healthbars to parent reference

hi!

I am currently working on an rts tutorial by lithex on youtube, and mixed it with a tutorial from Liamacademy.

i have some instances of units using various classes to construct the unit with all its stats, and i just finished making health bars with a lerp in it.
the units look like this

Sentinelunit
-Statdisplay
–canvas
—HealthBar

previously i would pass an healthbar reference in the editor to its respective unit for calling a
HandleHealth function, and then parent it to a mother canvas to centralize all those canvas.
does anyone have a pointer for me on how to call the right unit and update its healthbar?

    private void HandleHealth()
    {
        HealthBar.SetProgress(currentHealth / maxHealth);

        if (currentHealth <= 0)
        {
            Die();
        }
    }

previously i would call this function on a unit itself and then it would update the healthbar. but now i want to call this from a centralized script so each unit doesnt have to do this on its own and my player and enemy unit stay clean. should i generate a list of units and calculate this for each of them,
or am i just missing something like a reference call?

sorry for the chaotic explanation and thank you in advance.
Ed.

OK - big design suggestion coming up…

You are going to hit what we call a dependency problem. This is where one bit of code needs to know about another bit of code and you lose the ability to create standalone units of function. Eventually, all the code is entangled and it’s hard to write, hard to follow and hard to maintain. Think of the following case:

A player takes a hit. As a result, you need to update health stats, change the health bar, potentially change their mobility, play some audio, play an animation, tell AIs, in case their behaviour changes with a weakened opponent and so on. That’s a lot of calls in one place and creates lots of knots in your code. How to prevent this?

This is where events come in. Rather than call all these separate functions, the TakeHit code announces that there has been a hit by creating a custom event. Any modules that are interested “subscribe” to this event and can act accordingly. This is also great for building because, if you haven’t written your audio code yet, you don’t subscribe. More importantly, when you do write your audio code, you don’t have to revisit your “TakeHit” code because it has created the event and that’s all it ever needed to do.

I previously wrote an answer about events, which might help. If it doesn’t, you can find plenty of online tutorials about them. When you’ve understood events, you’ll wonder how you ever coped without them…