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.
01 | local Player = game.Players.LocalPlayer |
02 | local Character = Player.Character or Player.CharacterAdded:Wait() |
03 | local HealthBar = script.Parent |
05 | local Humanoid = Character:WaitForChild( "Humanoid" ) |
06 | local Health = Humanoid.Health |
08 | Humanoid.HealthChanged:Connect( function (newHealth) |
09 | HealthBar.Size = UDim 2. new((newHealth/Humanoid.MaxHealth), 0 , 1 , 0 ) |
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.