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

Why is the healthbar broken in actual game?

local plr = game.Players.LocalPlayer
local human = plr.Character:WaitForChild("Humanoid")

human.Changed:connect(function(prop)
    if prop == "Health" or prop == "MaxHealth" then
        script.Parent:TweenSize(UDim2.new(human.Health/human.MaxHealth,0,0,25),"Out","Quad",0.3,true)
    end
end)

So I have a custom health bar, and it works fine in test in studio, but when i go to team test or local server it gives me this error: 01:29:51.034 - Players.Activatted.PlayerGui.ScreenGui.Frame.HealthBackground.HealthBox.LocalScript:3: attempt to index field 'Character' (a nil value) I tried adding a wait, but it broke the script completely

4 answers

You are calling the character before it is even loaded.

A simple fix would be:

player_here.CharacterAdded:wait()

More information about this: http://wiki.roblox.com/index.php?title=API:Class/Player/CharacterAdded

So to fix your script:

local plr = game.Players.LocalPlayer
local human = plr.CharacterAdded:wait():WaitForChild("Humanoid")

human.Changed:connect(function(prop)
    if prop == "Health" or prop == "MaxHealth" then
        script.Parent:TweenSize(UDim2.new(human.Health/human.MaxHealth,0,0,25),"Out","Quad",0.3,true)
    end
end)

You're calling the character when it hasn't loaded yet. Here's what I do to make sure it's loaded:

local human = game.Workspace:WaitForChild(plr.Name)

Try adding this varible:

local char = plr.Character or plr.CharacterAdded:wait()

then change this line:

plr.Character:WaitForChild("Humanoid")

To:

char:WaitForChild("Humanoid")

You can wait until everything is loaded, by doing this before the rest of your script.

repeat wait() until game:GetService('ContentProvider').RequestQueueSize == 0

What it basically does, it waits until the request queue size is 0, because when a game starts, it has to load everything.

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