Health Bar

In this tutorial we will learn how to create a health Bar in Unity's Unlit Shader.


[IMPORTANT]
If you are visiting this website for the very first time, please have a look at the first tutorial, it would help you to understand this tutorial better. Click Here!

Project Setup

First add a plane then rotate it's face toward camera, or set the plane rotation to (90, 180, 0).
Add a unlit shader and apply it to a material, and apply that material to the plane.

open the Unlit Shader in Visual Studio.

Bootstrap Themes



With this rotation of plane, the origin of i.uv is bottom left corner.

Bootstrap Themes

First we will shift the origin to center. (mentioned with yellow cell)
If you don't know how to shift the origin to center, or how to draw a box, you could follow this tutorials for understanding.
Click Here !

Next is to draw a rectangle. (mentioned with orange cell)
UV.x have range of values (-0.5 . -0.25 . 0.0 . 0.25 . 0.5) from left to right.
UV.y have range of values (-0.5 . -0.25 . 0.0 . 0.25 . 0.5) from bottom to top.

To draw the rectangle, we just have to check if the absolute values of UV.x & UV.y lies in this range or not
(abs(UV.x) < 0.45 && abs(UV.y) < 0.05)
abs() function return's only positive number, e.g if you input -4 it will return 4, if you input -8 it will return 8.

Bootstrap Themes
Bootstrap Themes
Bootstrap Themes

Next we will draw a rectangle smaller than the one we just created.(mentioned with green cell)

Bootstrap Themes
Bootstrap Themes

Now we will create the fill effect for the smaller rectangle.
We know that i.uv.x have range of values 0.0 ... 0.25 .. 0.50 .. 0.75 .. 1.0 from left to right.

(i.uv.x < 0.5) means if value of i.uv.x is less than 0.5 then set random color for pixel.
else means if value of i.uv.x is greater than 0.5 then set the pixel color to black.

In next section, we will control the fill amount & color from inspector.

Bootstrap Themes
Bootstrap Themes

Change Fill Amount & Color From Inspector

Just copy & paste the code (mentioned in the yellow cell) in your shader code.

Bootstrap Themes

To make the background transparent. Make changes in your shader code. (mentioned with yellow cells)
We are just setting the color alpha to zero.

So you could place the health Bar above your Player's head.

Bootstrap Themes