Why am I getting error: attempt to index nil with 'WaitForChild'

hi.

In my game, for some reason players are not spawning on the spawns, so I am trying to create a script to force them to go to the spawn when they join the game.

However, I am getting the error:
ServerScriptService.SpawnPlayerOnAdd:8: attempt to index nil with 'WaitForChild’

Here is my code:

local Players = game:GetService("Players")
Lobby = game.Workspace.storage.lobby


Players.PlayerAdded:connect(function(player)
	player.Character:WaitForChild("HumanoidRootPart").CFrame = Lobby.spawns:GetChildren()[math.random(1, #Lobby.spawns:GetChildren())].CFrame
end)

The character is nil (hasn’t been added) in this case.

local Character = Player.Character or Player.CharacterAdded:Wait()
-- Modify CFrame here.
player.CharacterAdded:Connect(function()

end

would also work. But Player.CharacterAdded:Wait() is more convenient.

Having only Player.CharacterAdded:Wait() won’t be as efficient, if the character is already added, it will yield forever.
The safest (and best) approach is the following code:

local Character = Player.Character or Player.CharacterAdded:Wait()

yep. Since if one is nil, the other is not, the character would still be defined by the one that is not nil.
Adding if Character then may help but not needed.

What you’re saying is not making any sense, you’re basically agreeing with me (unless that was your point).
Regardless, this issue has been solved.

1 Like