Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Why won'y my health bar GUI script work?

I don't know what is wrong with this GUI?

char = script.Parent.Parent.Parent.Parent.Character
hum = char.Humanoid
hum.Changed:connect(function()
	script.Parent.HealthBar.Size = UDim2.new(hum.Health/hum.MaxHealth,0,1,0)
end)

1 comment

0

What does the output say, or what is the problem? Does it say there's an error with a script? Or does it just not change size? Or does it change to the wrong size? If you could provide us with this, it may help us answer.

2 answers

✓ Accepted answer

LocalPlayer

First off, if you are dealing with a GUI and performing a task as simple as this, you should use a LocalScript to help reference the player with much more easily.

Using a local-script allows you to use 'LocalPlayer', a simple shortcut to finding the Player on the client.

local player = game.Players.LocalPlayer
print(player.Name)
--Prints the players name

Character

Also, be careful, the players character may not always have spawned as local-scripts load faster than most things in a game.

To make sure the character is ready, we can do a :wait() on the CharacterAdded event if the character hasn't been found:

local player = game.Players.LocalPlayer
local char = player.Character or player.CharacterAdded:wait()
print(char.Name)
--Will print the Characters Name

Using What We've Learned

Now, let's combine all that and fix your script:

local player = game.Players.LocalPlayer
local char = player.Character or player.CharacterAdded:wait()
local hum = char:FindFirstChild("Humanoid")
hum.HealthChanged:connect(function(health)
    script.Parent.HealthBar.Size = UDim2.new(health/hum.MaxHealth,0,1,0)
end)

--HealthChanged is a special event fired only when the Health is Changed

1 comment

0

It worked but it's coming from the wrong side also how would I invert it so when I have maxhealth it shows no health? http://www.roblox.com/unnamed-item?id=234869235

char = script.Parent.Parent.Parent.Parent.Character
hum = char.Humanoid
hum.Health.Changed:connect(function()
    script.Parent.HealthBar.Size = UDim2.new(hum.Health/hum.MaxHealth,0,1,0)
end)

1 comment

0

Don't use .Changed on properties. You have to use it on the Object itself.

This discussion is preserved as it was. New answers, comments, and votes are closed.