game.Players.PlayerAdded:connect(function(p) local c = p.Character for i, chara in pairs(c:GetChildren()) do if chara:IsA("Hat") then chara:Destroy() end end end)
I have this script that gets the players character and gets rid of their hats when they join the game. It works up to line 3, when it says that C is nil. Why is that? I'm not 100% sure that p.Character is how you get the character from the player, but that's what it says everywhere I went for help.
Someone help me with this?
Your problem is that the character hasn't loaded yet, when the script reads line 3
, which uses the GetChildren
function, it reads 'c' as 'nil' since 'c' hasn't loaded yet.
There are a couple ways of doing this, but the ultimate goal is to yield the script until the character isn't nil. An easy solution is to use a CharacterAdded
event, which is precisely like the PlayerAdded
event, but for characters!
game.Players.PlayerAdded:connect(function(p) p.CharacterAdded:connect(function(c) --CharacterAdded event for i, chara in pairs(c:GetChildren()) do if chara:IsA("Hat") then chara:Destroy() end end end) end)
Here try this, I added a wait
EDIT:Waiting is essential because we want to make sure the character get loaded before doing anything else.
Also, Goulstem smells
game.Players.PlayerAdded:connect(function(Player) repeat wait() until Player.Character local Character = Player.Character for _, v in pairs(Character:GetChildren()) do if v:IsA("Hat") then v:Destroy() end end end)
Thank you