I have a custom health bar script that works perfectly in Test Solo in the Studio. When I try and play on a server, the code breaks. It returns the following error: Players.Player1.PlayerGui.Bottombar.HealthBarScript:9: attempt to index local 'character' (a nil value), line 9.

Here is my full code:

local player = game.Players.LocalPlayer
local character = player.Character

function round(num)
	return math.floor(num +.5)
end

while true do
	local humanoid = character:FindFirstChild("Humanoid")
	if humanoid ~= nil then
		local healthBar = script.Parent.CentralBlock.HealthBar
		local healthLabel = script.Parent.CentralBlock.VariableHealthLabel
		local healthNumber = round(humanoid.Health)
		healthBar.Size = UDim2.new(0, (humanoid.Health*2), 0, -4)
		healthLabel.Text = healthNumber
--		print(healthNumber)
	end
	wait()
end

Any ideas to fix this?

4 comments

0

Might I suggest adding "or player.CharacterAdded:Wait()" to line 2?

0

My assumption is the script might be trying to collect the character before it exists. Using :Wait() on an event will return the value originally expected in a :Connect() function. Having the or in place will have the script pick the existing of the two.

0

i have no clue

0

That worked perfectly, thanks! @M39a9am3R