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

Why is the healthbar broken in actual game?

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

Log in to vote
1
Answered by
VoltCode 101
6 years ago

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)

Ad
Log in to vote
0
Answered by 6 years ago

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)

Log in to vote
0
Answered by
sad_eyez 162
6 years ago

Try adding this varible:

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

then change this line:

plr.Character:WaitForChild("Humanoid")

To:

char:WaitForChild("Humanoid")
Log in to vote
0
Answered by 6 years ago

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.

Answer this question