Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

how do I fix this custom health bar issue?

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?

4 comments

0

Wouldn't it be local healthPercentage = character.Humanoid.MaxHealth - health

0

no that would be how much health is remaining. If i have 50% of my health left I want 50% of the bar to be filled, which is what divide currentHealth by maxHealth does

0

Use this for reference point to: https://developer.roblox.com/en-us/api-reference/event/Humanoid/HealthChanged I think this will help you.

0

what exactly is the problem here? is it that the bar doesnt move, is it a problem in what direction it moves in, etc.

1 answer

✓ Accepted answer

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!

3 comments

0

you could also just do:local character = player.Character or player.CharacterAdded:Wait()

0

thank you so much for this, it worked exactly how I wanted it to

0

I now realize I was very vague when asking the question lol but Im glad you knew what was going on

This discussion is preserved as it was. New answers, comments, and votes are closed.