Show a Health Bar
π― Goal
Make a UI slider follow an object’s health.
π§° What You Need
Health- A UI
Slider
πͺ Steps
Create a slider
Add GameObject > UI > Slider. Keep Min Value 0 and Max Value 1, and set Value to 1 so the bar starts full. Turn off Interactable so players can’t drag it.
Hook On Health Changed
On the Health, click + under On Health Changed, drag the slider into the object field and pick Slider > value from the Dynamic float list at the top. Health is passed from 0 to 1, so it matches the slider’s range.
Style the bar
Delete the slider’s Handle Slide Area, then color the Background and the Fill, for example red behind green.
π Inspector Settings
| Field | What it does | Set it to |
|---|---|---|
| On Health Changed | Raised with health from 0 to 1 | Slider.value (dynamic) |
π§ͺ Example
The Simple Duck scene has a UI slider set from the duck’s On Health Changed. The Hitbox Boss and Health Pickup scenes use the same setup.
π‘ Tips
- On Health Changed only fires when health changes, so set the slider’s starting Value to match.
ResetHealth()raises On Health Changed with1, so the bar refills when a player respawns.- For a bar above an enemy, use a World Space canvas as a child of the enemy. It needs a small script to turn it toward the camera.
- Pick Image > fillAmount instead of a slider for a filled image bar.