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

health bar script will work in studio but not in real game?

local this = script.Parent
local plr = game.Players.LocalPlayer
local char = plr.Character
	local human = char.Humanoid

local function round(n)

	return math.floor(n + 0.5)

end



	
human.HealthChanged:connect(function()
	local hp = round(human.Health)
	this.Size = UDim2.new(hp/125,0,0.7,0)
end)
	end)
		

this is a local script inside of a playergui

1 answer

Well there could be multiple things wrong. Here is a tip of advice. Instances do NOT exist instantly (especially in game).

You're trying to index instances that yet do not exist. (Such as the player's Character and their humanoid)

Also you have an extra "end)"

You want to wait for the character to exist and its humanoid. For the character we can use CharacterAdded and then :Wait() for it to yield the character. For the humanoid we can use :WaitForChild("Humanoid") on the char


local this = script.Parent
local plr = game.Players.LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local human = char:WaitForChild("Humanoid")

local function round(n)
	return math.floor(n + .5)
end

human.HealthChanged:Connect(function()
	local hp = round(human.Health)
	this.Size = UDim2.new(hp/125, 0, 0.7, 0)
end)

3 comments

0

there is still an error on line 3 but whatever

0

You declared that LocalPlayer would be plr and then you switched to player? Fix your code.

0

My mistake, I'm used to using player and I was using plr for the sake of OP

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