Small tip, putting a health bar on enemy characters

I’ve been looking into having a healthbar on enemy characters for a while and didn’t really find a good or working solution. Using a slider for the player is fine, but if you want to have it on your enemy it gets messy with it requiring a canvas.

After trying different things it seems it’s possible to achieve it in an easy way. On my enemy character I’ve added an empty child game object. Added a spriterenderer, that has a sprite shaped a s a rectangle. I’ve set the scale of the rectangles X to 1.2 (this value represents the enemy’s health which is set as 120). Then in my update script I have simply this:

The only disadvantage for now is that while the healthbar does decrease, it decreases towards the center.

Hopefully this may be helpful for someone looking to implement something similar. I’m sure there may be a better way to achieve this, and if so, I’d love to hear it!

3 Likes

Very nice solution!
Perhaps you could create another gameobject inside the healthbar at the left limite of the bar, and you could compare the diference of the position between this New object and the Center of the healthbar, and you can create a variable that receives the changes to this diference as the healthbar bar decreases and uses it to translate the Healthbar to the left

There is a way to use sliders too, but you would have to create it inside a canvas and set the canvas to world position mode

I did some more tinkering and it now translates to the left. All that needed to change was the sprite that represents the healthbar, in the inspector change the pivot of that to left instead of center and it now works correctly.

3 Likes

Very nice! Way easier than I thought.

Privacy & Terms