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
local player = game.Players.LocalPlayer local unitFrame = script.Parent local healthBar = unitFrame.HealthBarContainer.HealthBar player.CharacterAdded:Connect(function(character) local humanoid = character:WaitForChild("Humanoid") humanoid.HealthChanged:Connect(function(health) local healthPercentage = health / character.Humanoid.MaxHealth healthBar.Size = UDim2.new(healthPercentage, 0, 1, 0) end) 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:
local player = game.Players.LocalPlayer local unitFrame = script.Parent local healthBar = unitFrame.HealthBarContainer.HealthBar local function CheckHealth(character) local humanoid = character:WaitForChild("Humanoid") humanoid.HealthChanged:Connect(function(health) local healthPercentage = health / humanoid.MaxHealth healthBar.Size = UDim2.new(healthPercentage, 0, 1, 0) end) end if player.Character ~= nil then CheckHealth(player.Character) -- If the character is found, it runs the function and gives the character. end 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!