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

HealthBar not functioning properly?

So I am trying to make a HealthBar according to the player's Health. And I made this script, but its not working for some reason. Any help? --HealthBar script


local Player = game.Players.LocalPlayer
local PlayerHealth = Player.Character:WaitForChild("Humanoid").Health
game.Players.PlayerAdded:Connect(function()
	while true do
	wait()
	
	local Health = PlayerHealth 
	local MaxHealth = Player.leaderstats.MaxHealth
	
	local math = ( Health / MaxHealth )
	
	script.Parent:TweenSize(UDim2.new(math,0,1,0),"Out","Quad",.25)
end
end)

--MaxHealth script


game.Players.PlayerAdded:Connect(function(player)
		local leaderstats = Instance.new("IntValue", player)
		leaderstats.Name = "leaderstats"
		leaderstats.Parent = player
		
		local MaxHealth = Instance.new("IntValue", leaderstats)
		MaxHealth.Name = "Max Health"
		MaxHealth.Value = 100
	end)

2 comments

0

Line 07 should be changed to: local Health = Player.Character:WaitForChild("Humanoid").Health

0

Still not working. :C

2 answers

Assuming MaxHealth inside the leaderstats is a value instance, it should be local MaxHealth = Player.leaderstats.MaxHealth.Value (on line 8)

3 comments

0

Still

0

any output?

0

Nope, not at all.

So first, I don't think you really need to be tracking the MaxHealth of a player with an IntValue. The player's character's humanoid already has a value for that.

What you would want to do is have your...

game.Players.PlayerAdded:Connect(function(player)
	...
end)

But also character added event inside...

player.CharacterAdded:Connect(function(character) 
	...
end)

From there you would get the humanoid...

local humanoid = character.Humanoid

And then have a humanoid health changed event...

humanoid.HealthChanged:Connect(function(health)
	
end)

Inside that you would do your calculations...

humanoid.HealthChanged:Connect(function(health)
	local percentage = health / humanoid.maxHealth
	-- From here you can't change the player's guis from the server side so you will have to fire a RemoteEvent to the client and change the UI stuff there
end)
-- Client Local Script

RemoteEvent.OnClientEvent:Connect(function(percentage)
	HealthBar:TweenSize(UDim2.new(percentage,0,1,0),"Out","Quad",.25)
end)

That's how you would do it directly from the server side, but you could also do it entirely from a Local Script since whatever happens to the player's health on the server will replicate to the client. Where you would eliminate the playeradded, and do everything I just said on the client side.

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