Project 566: Custom Health Bar

8. Write a function to update the health bar

This function should set the size of the health bar equal to the player's current health.
Starting point file for this challenge

Steps

1. Create a function called HealthUpdate with no parameters

... or name it something similar! HealthUpdate makes sense, because the function is working to update your health bar.
function healthUpdate ()

2. Hit return to create an "end" to your function

Anything written between the last parentheses and the "end" will be the instructions for your HealthUpdate function.

3. Reference the size of your health bar

Inside the function, you’ll need to reference your healthBar variable, and then find its Size property.
healthBar.Size

4. Set the size to a new size

Set the last line you wrote equal to a new size.

The kind of coordinate you’ll use is called a UDim2.

(All this means is it’s a number that will represent the X and Y dimensions. It’s a kind of coordinate used in building GUI’s.) 
UDim2.new()

5. Fill out the parameters of the UDim2

Now it’s time to specify exactly what the new size of our health bar will be. The UDim2 has a lot of parameters so it can build the specific size you want. 

In order, the parameters will be: X scale, X offset, Y scale and Y offset.

  • We want the X scale, or the width, to represent how much health our player has, so write humanoid.Health for the first parameter.
  • The X offset should be kept to 0 as always.
  • The Y scale, or the height, should match the parent’s scale. What number do we use to make a child match the parent scale?
  • Finally, the Y offset should also stay 0.

UDim2.new(humanoid.Health, 0, 1, 0)

6. Call the function when the player’s health changes

Grab the “humanoid” variable, and use it to detect the “Changed” event. Connect with your HealthUpdate function every time the “Changed” event runs. 
humanoid.Changed:connect(healthUpdate)