The health bar is a think that show the player health only the client can see it
Setting up the Health Bar
The Size and the Position of the Frame in the red border Should Be Like this:
Enable The Reset on Spawn Property in the Health Gui
The Script
Put The Script in the localscript
repeat wait() until game.Players.LocalPlayer.Character --Wait For The Player Character
repeat wait() until game.Players.LocalPlayer.Character:FindFirstChild("Humanoid")--Wait For The Player Character Humanoid
while wait() do --Loop
script.Parent.Size = UDim2.new(game.Players.LocalPlayer.Character.Humanoid.Health/game.Players.LocalPlayer.Character.Humanoid.MaxHealth,0,1,0) --Set The Size Of The Frame To The PlayerHealth
end
You should try using variables and events in your code! This is a cleaner, probably more efficient, way to do the same thing (without loops):
--[[
If the local player has a character, use it. If not, wait
until it's spawned.
You might use a `while` loop in place of the `WaitForChild`
call, if you can't guarantee "Humanoid" is the name
of the Humanoid object.
--]]
local Player = game:GetService("Players").LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")
local Healthbar = script.Parent
--[[
Wrap the updater up in a function so we can reuse it.
We clamp the health value to prevent it from going
below 0 or above 1.
You may swap the values of `.fromScale` if you wanted
a vertical healthbar.
--]]
local function UpdateHealthbar()
local health = math.clamp(Humanoid.Health / Humanoid.MaxHealth, 0, 1)
Healthbar.Size = UDim2.fromScale(health, 1)
end
--[[
Update the healthbar in case their health is not 100%
when the script loads.
--]]
UpdateHealthbar()
--[[
Listen for changes in Health or MaxHealth
--]]
Humanoid:GetPropertyChangedSignal("Health"):Connect(UpdateHealthbar)
Humanoid:GetPropertyChangedSignal("MaxHealth"):Connect(UpdateHealthbar)
Nice tutorial! Health bars are a fun and simple start for people new to scripting. Though, I have a little feedback for this tutorial. I feel that the script in this tutorial could do well to teach about events, variables, and functions, all important principles to programming in Roblox and in general (and all of which would come into play when scripting a health bar). Basic or not, I believe that practical tutorials like these should reflect good practices and design patterns (especially when your tutorial is meant for absolute beginners!)
A bit late to the party but, in case anyone is wondering why this script isnβt working for them.
-- old one
local function UpdateHealthbar()
local health = math.clamp(Humanoid.Health / Humanoid.MaxHealth, 0, 1)
Healthbar.Size = UDim2.fromScale(health, 1)
end
-- my version
local function UpdateHealthbar()
local health = math.clamp(Humanoid.Health / Humanoid.MaxHealth, 0, 1)
Healthbar.Size = UDim2.fromScale(340*health, 44) -- 340 is what size i want for my ui to be when max health, 44 is my ui height.
end