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

How do I make it so that Character is not equal to nil?

Asked by 6 years ago

I am trying to create a Health GUI but when I test it, nothing happens and developer console says character is a nil value. Please help and thank you. Here is my local script:

local humanoid = game.Players.LocalPlayer.Character.Humanoid

humanoid.Changed:Connect(function()
    local critical = humanoid.MaxHealth/4
    if humanoid.Health <= critical then
        script.Parent.BackgroundColor3 = Color3.new(255,0,0)
    else
        script.Parent.BackgroundColor3 = Color3.new(0,255,0)
    end
    script.Parent.Size = UDim2.new(0,(humanoid.Health/humanoid.MaxHealth*225),0,40)
end)

1 answer

Log in to vote
0
Answered by
Amiaa16 3227 Moderation Voter Community Moderator
6 years ago

You need to wait for the character to be created. You can use CharacterAdded event for this purpose.

local plr = game:GetService("Players").LocalPlayer
local char = plr.Character or plr.CharacterAdded:Wait()
local humanoid = char:WaitForChild("Humanoid")

humanoid.Changed:Connect(function()
    local critical = humanoid.MaxHealth/4
    if humanoid.Health <= critical then
        script.Parent.BackgroundColor3 = Color3.new(255,0,0)
    else
        script.Parent.BackgroundColor3 = Color3.new(0,255,0)
    end
    script.Parent.Size = UDim2.new(0,(humanoid.Health/humanoid.MaxHealth*225),0,40)
end)

0
Thank you. SweetNoodleSoup 14 — 6y
Ad

Answer this question