Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by
Plieax 66
6 years ago
Edited 6 years ago
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

Log in to vote
0
Answered by 6 years ago
Edited 5 years ago

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)
0
there is still an error on line 3 but whatever Plieax 66 — 6y
0
You declared that LocalPlayer would be plr and then you switched to player? Fix your code. Zafirua 1348 — 6y
0
My mistake, I'm used to using `player` and I was using `plr` for the sake of OP EpicMetatableMoment 1444 — 5y
Ad

Answer this question