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
3 years ago

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

local Player = game.Players.LocalPlayer
local Character = Player.Character
local HealthBar = script.Parent

local Humanoid = Character.Humanoid
local Health = Humanoid.Health

Humanoid.HealthChanged:Connect(function(newHealth)
    HealthBar.Size = UDim2.new((newHealth/Humanoid.MaxHealth), 0,1, 0)
end)
0
I recommend checking this out: https://www.youtube.com/watch?v=3mZbYbuUMuQ KillerWolfie2112 12 — 3y

3 answers

Log in to vote
1
Answered by 3 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.

local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local HealthBar = script.Parent

local Humanoid = Character:WaitForChild("Humanoid")
local Health = Humanoid.Health

Humanoid.HealthChanged:Connect(function(newHealth)
    HealthBar.Size = UDim2.new((newHealth/Humanoid.MaxHealth), 0,1, 0)
end)

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 3 years ago

Use

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

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

Log in to vote
1
Answered by 3 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:

local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local HealthBar = script.Parent

local Humanoid = Character:WaitForChild("Humanoid")

Answer this question