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)
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.
Use
Humanoid:GetPropertyChangedSignal("Health"):Connect(function()
instead of what you put for line 8 of your code :)
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")