- Home /
How to canvas health bars on top of every alive unit on screen??
I've seen many posts related, but non has worked the way I want to. I want to create a health bar asset (the health bar images, one on top of the other, sliding left to simulate health reduction) and asign one health bar asset to each unit (following eath unit) that is currently on screen "isVisible;" and alive "GetComponent().alive == true;". If possible, all health bars to show on a single canvas.
I'm having a hard time linking the objects with the canvas asset, can't even make the health bar asset appear on screen. I don't even know how to approach this... I'm pretty new to all this programming thing. Can anyone give me some advice on how I can achieve something like all this I described here??
Answer by AlwaysSunny · Apr 08, 2015 at 02:46 AM
In this case, I'd want a manager for any UI element that should be driven in world space, such as health bars, objective indicator icons, speech bubbles... Anything like that falls under one logical umbrella: World-space UI elements that come and go as needed.
Then there are screen-space UI elements that come and go as needed; e.g. prompts or feedback messages that appear for a moment; I'd probably manage them separately. Then there's screen-space elements that don't need dynamic positioning, such as a HUD, which I'd want in a third script. These three scripts I'd tie to a singleton UI manager which I could call anywhere in the project.
Each script holds prefabs of each unique UI object in the game, and will expose public methods which streamline the creation of the requested object. Ideally you want to be able to request the objects with a single line of code:
myHealthBar = UIMan.WorldSpaceTemps.Create("HealthBar", thisAgent);
Decide who will make the decision about requesting a new temporary world-space health bar; isVisible and isAlive and myHealthBar == null sound like fine checks; if all three are true, request a new health bar from the world-space-ui-manager. The new health bar could be tracked in a collection of active health bars and/or handed to the corresponding agent to manage, e.g. if !isVisible or !isAlive and myHealthBar != null, destroy myHealthBar.
The health bar object can be as complex as you like, but give it its own UIHealthBar script so you can manage that complexity with ease. It can position itself to correspond to its agent's world position, and set its own slider values based on its agent's health percentage. Keeping a collection of them in the world-space-ui-manager will allow group changes like destroying all health bars when the game ends.
Your answer
![](https://koobas.hobune.stream/wayback/20220613192419im_/https://answers.unity.com/themes/thub/images/avi.jpg)