Top Down Shooting Game (part 10)

Since my previous post, I’ve added health bars for enemies and players but I haven’t gotten it working yet. However, the way I did it to create the health bar was using images and I couldn’t get the health bar to work. So today I created a health bar with a slider and made it work for enemies and players.

In the Unity

The first step in adding a health bar to the enemy is to create a Slider UI element as a child of the enemy object. To do this, right-click on the Enemy object, navigate to UI -> Slider, and rename it to Health_Bar. By default, the slider comes with Background, Fill Area, and Handle Slide Area, but we only need the Background and Fill Area for the health bar. So we deleted the Handle Slide Area.

Enable Interactable in Health_Bar.

Change the Background Color to Red and the Fill color to Green.

In FloatingHealthBar Script

In Unity, create a script called FloatingHealthBar. Inside the script, create a [SerializeField] private Sliser slider; variable. This allows us to assign the slider component in the Unity Inspector without making it public. Create a function called UpdateHealthBar and set slider.value = currentValue/ maxValue.

In Enemy Script

Inside this script, add two [SerializeField] variables: one for the current health and one for the maximum health. And a healthBar reference the FloatingHealthBar script, which allows us to update the health bar UI based on the enemy’s current health.

And in the Start() function, use the GetComponentInChildren<FloatingHealthBar>() to assign the healthBar. This method automatically searches for the FloatingHealthBar component on any child of the enemy object.

In the GetTarget(), make the health = maxHealth and call the UpdateHealthBar. Which mean it is fill full the health before it is got shot.

And in the OnCollisionEnter2D(), call the UpdateHealthBar. It will call the FloatingHealthBar to update the enemy’s health bar.

In the Unity

In the Health_Bar, move the Slider to the FloatingHealthBar script.

The Health Bar is work after you run the game.

I tried setting up the same health system for the player as I did for the enemy, but it didn’t work and I got a lot of errors. I’ll work on it later.

Tags:

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *