I got this code sample from an article on Roblox developer:
here is the code, I basically copied everything perfectly- other than changing the size and position
01 | local player = game.Players.LocalPlayer |
02 | local unitFrame = script.Parent |
03 |
04 | local healthBar = unitFrame.HealthBarContainer.HealthBar |
05 |
06 | player.CharacterAdded:Connect( function (character) |
07 | local humanoid = character:WaitForChild( "Humanoid" ) |
08 | humanoid.HealthChanged:Connect( function (health) |
09 | local healthPercentage = health / character.Humanoid.MaxHealth |
10 | healthBar.Size = UDim 2. new(healthPercentage, 0 , 1 , 0 ) |
11 | end ) |
12 | end ) |
I'm thinking maybe this is outdated? what should I change?
Unsure if I'm 100% correct here but I think the character is being added before the .CharacterAdded event is set up. This might be because GUIs and local scripts put in StarterGui only load after the character is loaded. You could try getting the character directly first and if it isn't nil, use that character.
This is what I did to fix it:
01 | local player = game.Players.LocalPlayer |
02 | local unitFrame = script.Parent |
03 |
04 | local healthBar = unitFrame.HealthBarContainer.HealthBar |
05 |
06 | local function CheckHealth(character) |
07 | local humanoid = character:WaitForChild( "Humanoid" ) |
08 | humanoid.HealthChanged:Connect( function (health) |
09 | local healthPercentage = health / humanoid.MaxHealth |
10 | healthBar.Size = UDim 2. new(healthPercentage, 0 , 1 , 0 ) |
11 | end ) |
12 | end |
13 |
14 | if player.Character ~ = nil then |
15 | CheckHealth(player.Character) -- If the character is found, it runs the function and gives the character. |
16 | end |
17 |
18 | player.CharacterAdded:Connect(CheckHealth) -- If the character is nil or is respawning, this should run the function and give the new character once the character spawns. |
Hope this helped! If you have any questions, just comment!