Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Why won'y my health bar GUI script work?

Asked by
Rdite 30
9 years ago

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)
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. dyler3 1510 — 9y

2 answers

Log in to vote
1
Answered by 9 years ago

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

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 Rdite 30 — 9y
Ad
Log in to vote
0
Answered by 9 years ago
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)
0
Don't use .Changed on properties. You have to use it on the Object itself. DigitalVeer 1473 — 9y

Answer this question