Здоровье персонажа / Health Bar
Будем делать индикатор здоровья персонажа или как еще говорят, полоска здоровья. В общем, главный приоритет для нас, это удобство использования и настройки. Это улучшенный вариант бара, который мы публиковали ранее. Кроме всего прочего, рассмотрим, как быстро настроить стандартный слайдер, буквально за пару минут, для нашего индикатора. Основные возможности скрипта: установка уровня здоровья, от нуля и до нужного значения; регулировка ширины бара, относительно разрешения экрана; возможность размещать индикатор как слева, так и справа; быстрый доступ к текущему значению и функции изменения значения здоровья, из любого другого скрипта.
Преступим, первым делом добавим слайдер и настроим его, GameObject > UI > Slider:
И выключаем у него интерактивность, для того, чтобы невозможно было взаимодействовать со слайдером, например, мышкой.
В слайдере удаляем объект Background и выбираем Fill Area, настраиваем как на криншоте:

Тут же, находим объект Fill и настраиваем так же.
Далее, берем Handle Slide Area и делаем тоже самое, что и с предыдущим объектом. Последний штрих, находим Handle, ставим ширину на единицу, а альфа канал изображения на ноль, в общем как показано ниже:

Вот и всё. Полоска здоровья нашего персонажа готова, разместите слайдер в нужной части экрана и двигаемся дальше.
Создаем C# скрипт HealthBar, цепляем его на пустой объект например:
В переменной slider указываем ранее созданный слайдер здоровья, если индикатор с правой стороны экрана, то обязательно ставим галочку isRight. Ширина width, чем больше значение, там меньше будет размер полоски, так как разрешение экрана по ширине тут, делится на данное значение.
Создание полосы здоровья

Приветствую, мои дорогие друзья! В данной статье мы рассмотрим реализацию полосы здоровья для Вашего персонажа. Создание полосы здоровья состоит из двух частей:
- ВИЗУАЛЬНАЯ ЧАСТЬ. Это то, как будет отображаться полоса здоровья в вашей игре.
- ПРОГРАМНАЯ ЧАСТЬ. Это непосредственно сам код c#, который будет динамически менять визуальную полосу здоровья.
Визуальная часть
Итак, для начала нам необходимо с помощью окна Hierarchy создать новый игровой объект типа UI – Canvas, в котором в дальнейшем будет размещаться наша полоса здоровья. После создания объекта Canvas, приступим к его настройке. Для этого жмём на игровой объект Canvas, и в окне Inspector проделываем следующие действия:
- В поле Render Mode выбираем Screen Space – Camera. Это нужно, чтобы наш канвас привязать к нашей игровой камере.
- В поле Render Camera перетаскиваем объект нашей камеры из окна Hierarchy.
- В поле UI Scale Mode выбираем Scale With Screen Size.
- В поле Reference Resolution указываем Х=1920 Y=1080. Если Вы создаёте игру для мобильных устройств, то установите Х=1080 Y=1920
Настройки канваса завершены. Теперь внутри этого канваса нужно создать нашу полосу здоровья. Полоса здоровья будет состоять из двух частей(спрайтов): полоса прогресса, и её рамка. Скачать эти спрайты можно по клике на ссылку <a download href="https://unityhub.ru/files/guides/BarProgress.zip">Скачать</a>.

Создание рамки
Создаём игровой объект типа UI – Image, называем его, например, Border, и помещаем его внутрь объекта Canvas. Далее в окне Inspector настраиваем данный объект. Для этого в поле Suorce Image загружаем изображение(спрайт) нашей рамки.
Создание полосы здоровья
Создаём ещё один игровой объект типа UI – Image, называем его, например, Bar, и помещаем его внутрь объекта Canvas. В окне Inspector настраиваем данный объект следующим образом:
- В поле Suorce Image загружаем изображение(спрайт) нашей полосы здоровья.
- В поле Image Type выбираем Filed.
- В поле Fill Method выбираем Horizontal.
- В поле Fill Origin выбираем Left.
- В поле Preserve Aspect ставим галочку, чтобы изображение имело пропорции оригинала.
На данном этапе всё! Чтобы убедиться что мы всё правильно сделали, попробуйте у объекта Bar изменить в Inspector-е значение поля Fill Amount используя ползунок. От таких манипуляций, размер полосы вашего здоровья на игровой сцене должен меняться, в зависимости от значения, указанного в поле Fill Amount. Если всё работает, значит на данном этапе Вы всё сделали правильно.
Программная часть
Перед тем, как мы перейдём к основному коду, предлагаю для начала создать файл типа скрипт C#, и назвать его, например, InfoPlayer. В данном скрипте мы будем хранить информацию о текущем и максимальном здоровье нашего игрока:
Не забудьте этот скрипт присвоить к игровому объекту вашего персонажа.
Но а теперь перейдёт к самому интересному. Как вы уже догадались, для динамического изменения полосы здоровья, нам нужно с помощью программного кода c# менять значение Fill Amount у нашего объекта Bar. Для этого создаём новый c# скрипт, с названием, например, HealthBar. Данный скрипт присваиваем к игровому объекту, в котором будем менять значение Fill Amount, а именно к объекту Bar. Весь код выглядит следующим образом:
Давайте разберём этот код по порядку.
Поскольку мы используем игровые объекты типа UI, то нам необходимо подключить дополнительную библиотеку:
Далее объявляем 2 переменные. Переменная healthBar будет хранить ссылку на компонент Image для того, чтобы менять в этом компоненте свойство Fill Amount. А в переменной player будем хранить ссылку на объект нашего игрового персонажа, чтобы извлекать из него информацию о текущем(HP) и максимальном(maxHP) здоровье персонажа.
В методе Awake() получаем ссылки на компонент Image и Player. Теперь в наших переменных имеется вся необходимая информация, для правильного отображения полосы здоровья:
Ну и в завершении, в методе Update() мы устанавливаем значение fillAmount исходя из данных о текущем здоровье игрока(player.HP) и о максимальном здоровье игрока(player.maxHP).
Всё, полоса здоровья готова! При изменении здоровья вашего персонажа, полоса здоровья автоматически будет уменьшаться либо увеличиваться. Если статья была полезной, буду рад вашим лайкам. Спасибо.
Create health Bar in Unity 3D
In one of the previous tutorial, we saw how to create radial progress bar. In this tutorial, we will see how to create health bar in unity 3D using similar steps.
Resources:
- Find the sample image used in the example here.
- Find the unity package of example here.
Step by step guide to create health bar in unity 3D
Step 1: Add Image to the scene
Create a new project and add a image to image game object in the scene. Set the width of the image to 200 and height to 20.
Step 2: Apply sprite to the image
Add a simple rectangular texture to the assets. Convert it to the sprite. Color of this texture is white.
Now, apply this sprite to the image.
![]()
Step 3: Change image properties
Select Image game object in scene and change it’s Image component property in the inspector.
- Change image type property to filled.
- Then, change fill method to Horizontal.

Step 4: Change fill amount
In the Image properties, we can see the fill amount. When we change this value then we can see how it’s visibility changes.
We will control this fill amount property using below script. Attach this script to the Image game object.
Unity Tutorials: How To Make a Health Bar in Unity!
One of the most common things that we see in video games is a health bar. Of course, if there’s no health in video games, then players will never lose. (Yes, I know there are games that don’t use “health bars” but they still use health to kill players, you get the point.)
Most health bars are displayed using HUD or Heads-up Display. If you’re not sure what it is, it’s the graphic that you see mostly at the top-left corner of the screen (depends on the game).
Kind of like this.

Of course, that’s not the only type of HUD that you will see in video games. There are moments that you will see the health bar placed at the top of the player’s character especially if the game is a MOBA or Multiplayer online battle arena.
Speaking of MOBA, we’re very happy to announce that we’re having a partnership with Raid Sha- just kidding.
On a serious note though, we’re very lucky that making a health bar is very easy to accomplish, special thanks to Unity for providing us game developers a UI system where we can easily modify each interface to display different kinds of things like Loading bar, power bar, time progress bar, etc.
In this tutorial, we’ll be guiding you on how to create a very simple health bar that you can EASILY apply to anything like player, enemy, objects or etc.
Video Tutorial
The following video tutorial can guide you on how to create a player health system with animation though it’s important to note that in this video, we have used a different approach to player health script. Feel free to watch this video:
Getting Started
If you have an existing project, feel free to use it for this lesson otherwise create a new project.
In our new scene, we’re going to create an empty game object and we’ll call it Player.

Once created, select the Player game object and navigate to the Inspector window and reset the transform component like below.

Next, click on the Add component button and look for Sprite Renderer using the search bar.

Once Sprite Renderer is added, navigate to it and click on the little circle beside the Sprite parameter. Then, look for Knob and select it like below.

If you have any sprites that you want to use for your player, feel free to use it.
Adding Health Points
Of course, before we can create the health bar we will need first to create the health points.
This is where we are going to base our health bar. If the player currently has 50/100 health points then our health bar should calculate it based on that data and should display a half health bar.
To start, we’re gonna need to create a new C# script and we’ll call it Health.cs .
Use the following code.
So in the code above, what we’re doing is we’re creating a set of functions that initialize the value of the current health of the player to the maximum. Then, we also have the function that gives damages to the player. So, if you take a look at the Update function, as you can see we’re checking if the Player hits the SPACE bar, if the player did, then the player will receive damage.
Creating the Health Bar
Now that we have our player health points set up, let’s begin working on displaying the actual health bar.
To start, navigate to your hierarchy, right-click and select UI then Image.

This will be creating a new canvas especially if there’s currently none in the scene. Inside the canvas, there will also be an image UI object created.
With all that being said, select your Canvas game object and press F key to show the entire canvas on the screen.
Next, select your Image game object and make sure that it is placed right at the center of the canvas like below.

Next, we’ll be changing the graphic being used in this object so download the PNG image provided below and import it to your project.
Pro tip: to import the downloaded file, just navigate to the file that you wish to import and then just simply drag it into your project window like below.

Another way to import your files is by going to your assets folder which is located in your project folder.
Make sure that once you have dragged the image onto your project files, you must change the import type to Sprite.
Once the image is imported, go back to your hierarchy, select the Image UI object and navigate to its Image component and change its Source Image to the image that we have just imported. The health bar.

Next, just below the Preserve Aspect check box, click the Set Native Size button.
This will resize the image based on the actual resolution of the image file.
Next, let’s rename our Image UI object to something like… Health Bar Border.

The next thing that we’re going to do is to create an empty game object inside the Canvas so right-click on the Canvas game object and select Create Empty .
Let’s rename this Empty game object to Health Bar
Next, with the Health Bar game object selected press T . This will enable the Rect Tool.

Now, resize the Health Bar to the same size as the Health Bar Border.

Next, drag the Health Bar Border game object to the Health Bar game object to make it as its child, like below.

Let’s create another Image, so with your Health Bar game object selected, right-click then navigate to UI then select Image.

By now, you should have the same hierarchy as below.

If you noticed, the image in the scene window is above the Health Bar Border sprite.

We don’t want it like that, we want our border to be displayed right above anything else so… to do that, just simply drag the Image object above the Health Bar Border game object like below.

We’re getting somewhere! Now let’s change the color of this image since this object will represent the actual bar for the player’s health point.
But before that, let’s rename first our Image game object to Health Bar Image because we don’t want it to call as Image all the time.
Nice! Now let’s select our Health Bar Image and navigate to its Image component.
In the color property, change its hexadecimal value from FFFFFF to DB2525 .

Now, we want our Health Bar Image to be the same size as its parent so to do that, go to its Rect Transform component and click on the box with the red cross in it. This will show you the anchor presets.
With the anchor presets being showed, hold ALT key, and select the stretch preset at the bottom-right corner of the preset’s window.

This will fill the entire Health Bar game object.
There’s a little issue though. As you can see below, the Health Bar Image is also showing at the corners of the Health Bar.

Fixing that is very simple. Just select the Health Bar Image, press T to enable the Rect Tool and just resize the Health Bar Image to where it won’t show beyond the border.

Just make sure to drag using the blue dot though instead of the anchors.
Next, let’s also fixed the border since it will also bug out if you try to scale the Health Bar game object like below.

To fix that, select the Health Bar Border game object and navigate to its Rect Transform component and click on the Anchor Preset button and select the preset at the bottom-right corner. Without pressing the ALT key.

With all that, you’ll be able to scale your Health bar to any size you want without worrying about its images.

Awesome! We’re getting there!
Using Slider UI for the Health Points
Now the next thing that we’re going to do is to make the Health Bar an actual health bar where the red fill can decrease or increase.
To do that, we’re going to use the Slider component.
So with your Health Bar selected, go to its inspector and click Add Component and look for Slider.

Next, we’re going to set the Slider component to the following values.
- Interactable is unchecked
- Transition is set to none
- Navigation is set to none
- Fill Rect, drag the Health Bar Image object to its value

By doing so, a new set of parameters will show up such as the direction of the slider, the minimum and the maximum value, and the actual value.
By sliding the value you will see that the Health Bar Image also gets affected.

Scripting the Health Bar
Now that we have everything set up, let’s start coding the actual health bar.
So with your Health Bar game object selected, click the Add Component and look for New Script. Select that and set the name of the script to HealthBar.

Once the script is created, open it with visual studio and copy the following code.
Save your scripts and go back to Unity.
Using the Script
Once all your scripts are saved, navigate back to your hierarchy and select your Player game object.
Then, drag the Health.cs script to its inspector to assign the script.
Go to its inspector and drag the Health Bar game object to the Health Bar parameter of the health script like below.

Still with your Player selected, navigate to the Tag dropdown and select Player.

If in case there is no Player option in the Tag dropdown, you may select the Add tag… option and add the Player tag yourself.
Save your scene and test your game.
Your player’s health should decrease whenever you hit your spacebar.
Well, technically this tutorial is over. With everything set up you should be able to take damages just by calling the Health script function DamagePlayer() with the amount of damage value that you want to send.
You can also move the Health bar to the top of the screen like below.
Just make sure to anchor the health bar to wherever position you want to put the health bar. For example, you want to put the health bar at the top-left corner, anchor the health bar at the top-left so the health bar will stay in the same position regardless of the screen resolution.

Conclusion
There you have it, you finally have a health bar that you can apply to your player. Of course, you can always modify the scripts, if you want to change the color of the health bar depending on the value of the health points, you can do that too using gradient.
10 Comments.
Nice and clear, thank you! Just one note. I as a noob struggled with that for a while. When you download your .png file you can’t directly assign it to your image object (under the canvas), because it requires a sprite, not a texture. So:
1. Click on the downloaded texture (.png)
2. In the Inspector top find ‘Texture Type’ and change it to ‘Sprite (2D and UI).
After you can drag it onto ‘Source Image’, it works.
Thank you for reading our tutorials and we truly appreciate that you’re finding our guides helpful.
Yes, we totally missed the part that the image should be set up and imported as Sprite instead of default texture.
We’ll get this article updated as soon as possible.
Thank you for pointint that out
I am having problems with the script, I added it to a player I already had. The health bar always shrinks itself and moves away from where I want it to go. Help?