Attempt to index nil with 'WaitForChild'?

Hi, I’m not sure what’s going on, but, I keep getting
15:59:46.590 - ServerScriptService.Classd:5: attempt to index nil with ‘WaitForChild’
when I play-test my game. It’s coming from this script in ServerScriptService

local Classdclass = game.ReplicatedStorage.Classdclass
local Teams = game:GetService("Teams")
local players = game.Players
Classdclass.Event:Connect(function(player)
		player.Character:WaitForChild("Shirt"):Destroy()
		player.Character:WaitForChild("Pants"):Destroy()
		wait(1)
		local Shirts = Instance.new("Shirt",player.Character)
		local Pants = Instance.new("Pants", player.Character)
		player.Team = Teams["Class-d"]
		Shirts.ShirtTemplate = "http://www.roblox.com/asset/?id=303911572"
		Pants.PantsTemplate = "http://www.roblox.com/asset/?id=303911192"
		player.Character.HumanoidRootPart.CFrame = CFrame.new(-311.74, 16.554, 1042.9)
end)

It has something to do with

player.Character:WaitForChild("Shirt"):Destroy()
player.Character:WaitForChild("Pants"):Destroy()

and it wouldn’t work when I do

player.Character.Shirt:Destroy()
player.Character.Pants:Destroy()
16 Likes

That error would indicate that the Character isn’t currently available at the time of that event being captured.

You’re attempting to index nil with WaitForChild. In other words, player.Character is resolving as nil. You should either check that the Character exists first or wait for the Character to exist.

5 Likes

You should add a player.CharacterAdded:Wait() to make sure the character is loaded

2 Likes

When I do that sometimes it works and sometimes it doesn’t

1 Like

when I do

local Classdclass = game.ReplicatedStorage.Classdclass
local Teams = game:GetService("Teams")
local players = game.Players
Classdclass.Event:Connect(function(player)
		player:WaitForChild(player.Character)
		player.Character:WaitForChild("Shirt"):Destroy()
		player.Character:WaitForChild("Pants"):Destroy()
		wait(1)
		local Shirts = Instance.new("Shirt",player.Character)
		local Pants = Instance.new("Pants", player.Character)
		player.Team = Teams["Class-d"]
		Shirts.ShirtTemplate = "http://www.roblox.com/asset/?id=303911572"
		Pants.PantsTemplate = "http://www.roblox.com/asset/?id=303911192"
		player.Character.HumanoidRootPart.CFrame = CFrame.new(-311.74, 16.554, 1042.9)
end)

I get the error
16:27:59.793 - Argument 1 missing or nil

1 Like

That’s not really how you wait for the player’s character. First, it states that error because the (player.Character) is a nil value.

To fix this, I suggest doing:

local character = player.Character or player.CharacterAdded:Wait()
41 Likes