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

Why does this health change script not work sometimes?

Asked by
QWJKZXF 88
4 years ago

I am trying to make a health script and it doesn't seem to work every time, how can I fix this?

01local Player = game.Players.LocalPlayer
02local Character = Player.Character
03local HealthBar = script.Parent
04 
05local Humanoid = Character.Humanoid
06local Health = Humanoid.Health
07 
08Humanoid.HealthChanged:Connect(function(newHealth)
09    HealthBar.Size = UDim2.new((newHealth/Humanoid.MaxHealth), 0,1, 0)
10end)
0
I recommend checking this out: https://www.youtube.com/watch?v=3mZbYbuUMuQ KillerWolfie2112 12 — 4y

3 answers

Log in to vote
1
Answered by 4 years ago

The reason your script doesn't work from time to time is because the local script is loaded before your character(avatar) came be fully loaded into the game. This in turn will result in the script not finding what it needs and therefore breaking.

What you need to do is the use the :WaitForChild() method are a way to let the script know it has to keep on waiting until it can find what it needs.

As said before, since the script loads first before the character, you are going to need the script to wait for the character.

01local Player = game.Players.LocalPlayer
02local Character = Player.Character or Player.CharacterAdded:Wait()
03local HealthBar = script.Parent
04 
05local Humanoid = Character:WaitForChild("Humanoid")
06local Health = Humanoid.Health
07 
08Humanoid.HealthChanged:Connect(function(newHealth)
09    HealthBar.Size = UDim2.new((newHealth/Humanoid.MaxHealth), 0,1, 0)
10end)

In case you are wondering why the character contains two components is because it is to account for two things, the character loads at the same time as the script, or the script loads before the character, hence the :Wait(), which will pause the script until an event(CharacterAdded) is fired.

Ad
Log in to vote
1
Answered by 4 years ago

Use

1Humanoid:GetPropertyChangedSignal("Health"):Connect(function()

instead of what you put for line 8 of your code :)

Log in to vote
1
Answered by 4 years ago

This could be caused by certain instances not being loaded whenever called. In order to make sure this is not the case, I would do this:

1local Player = game.Players.LocalPlayer
2local Character = Player.Character or Player.CharacterAdded:Wait()
3local HealthBar = script.Parent
4 
5local Humanoid = Character:WaitForChild("Humanoid")

Answer this question