Attempt to index nil with 'WaitForChild'

I made a script with intention to hide your group rank or not in my game, but the issue is it returns the “error attempt to index nil with ‘WaitForChild’” I don’t know why it returns it but this is the script I made.

local plr = game:GetService("Players").LocalPlayer
local character = plr.Character
local head = character:FindFirstChild("Head")
local rank = head:WaitForChild("RankUI").GroupRank

function Click()
	if rank.Visible == true then
		rank.Visible = false
		script.Parent.BackgroundColor3 = Color3.new(0.282353, 0.282353, 0.282353)
	else
		rank.Visible = true
		script.Parent.BackgroundColor3 = Color3.new(1, 1, 1)
	end
end

script.Parent.MouseButton1Down:connect(Click)

It is very simple, it first makes the definitions then it runs itself. However, Line 4 returns the error attempt to index nil with WaitForChild. This is part of a textbutton localscript by the way. Here’s a video with the error

None of the instances of a character are guaranteed to be added when client-side code starts executing so your declarations may be evaluating to nil, as in they can’t find the instances before they’re added. This is happening on line 4, so the issue is on line 3 where head evaluates to nil and then you attempt to call a method on the value “nil” which is erroneous.

BTW, WaitForChild isn’t anywhere in your script, so I think you meant FindFirstChild in the title.

There are a few ways to fix this. Ideally, for me, I leave all character stuff into the button itself as a lazy quick fix so the checks happen when the function runs.

local function Click()
    -- Declare head here
    -- Then declare rank here

    -- Then the rest of the code here
end
1 Like

Thank you! this worked.

Also, I pasted an older version of the code into the topic, thats why it was FindFirstChild instead of WaitForChild.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.