Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Help with getting character from player?

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?

2 answers

✓ Accepted answer

Your Problem

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.


Solution

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!


Code

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)

3 comments

0

Thanks for the answer, it gets me a bit farther but for some reason the hats don't get removed. Any reason why?

1

Wait, never mind. I just realized I need to give the hats time to load before they are removed. Thanks for the help!

0

Anytime

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

2 comments

0

Simply providing code doesn't broaden the asker's understanding of why they were wrong. Elaborate. Annotate.

0

I said I added a wait.. What I get for trying to help people :(

This discussion is preserved as it was. New answers, comments, and votes are closed.