Attempt to index nil with 'WaitForChild'

Greetings,

I don’t know what I am wrong… I added loading time because it had a hard time locating Character and other properties. The code and the error are shown down below:

game.Players.PlayerAdded:Connect(function(player)
	local loading_time = 60
	local energy = player:WaitForChild("leaderstats"):WaitForChild("Energy")
	local health = player:WaitForChild("Character", loading_time):WaitForChild("Humanoid", loading_time):WaitForChild("Health", loading_time)
	wait(2)
	while wait(20) and energy.Value > 0 do
		energy.Value = energy.Value - 1
		print(player.Name.. " has lost 1 energy, " ..energy.Value.. " more to go!")
	end
	while energy.Value == 0 and wait(10) do
		health.Value = health.Value - 5
		print(player.Name.. " has lost 5 health because of low energy! " ..health.Value.. " health left!")
	end
end)

Screenshot 2022-01-14 155424
Please help me, thanks.

Character is not a child of Player. It’s a property of Player.

1 Like

It worked fine without waitforchild (in the studio) but in the game it needs to have waitforchild because it loads a lot slower.

Instead of WaitForChild, you can use Player.CharacterAdded. CharacterAdded returns an RBXScriptSignal, so you can use the :Wait() method.

local char = player.Character or player.CharacterAdded:Wait()

Also your second while loop will never run, wrap the first one in a task.spawn function.

1 Like

Thanks for the CharacterAdded method. It’s working really well. But can you please show me in a more detailed perspective how should I replace in the script the wait() with the task.spawn? I have never used it before. Thanks once again!

task.spawn and coroutine.wrap create a Pseudo thread. All types of loop yield and since your first while loop runs forever, the second will never start. Pseudo threads prevent this.

task.spawn(function()
    while true do

    end
end)
while true do

end

Your original code will also only work once, if the character respawns it will stop deducting health.

1 Like

Ok, thank you a lot once again for the help! I really appreciate it.