Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Help with getting character from player?

Asked by
Scootakip 299 Moderation Voter
8 years ago
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

Log in to vote
-1
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
8 years ago

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)
0
Thanks for the answer, it gets me a bit farther but for some reason the hats don't get removed. Any reason why? Scootakip 299 — 8y
1
Wait, never mind. I just realized I need to give the hats time to load before they are removed. Thanks for the help! Scootakip 299 — 8y
0
Anytime Goulstem 8144 — 8y
Ad
Log in to vote
-1
Answered by
Im_Kritz 334 Moderation Voter
8 years ago

Please provide explanation with your answers. Simply posting code does not spread knowledge of integral scripting processes which helps people understand the logic and reasoning behind your answer.

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

0
Simply providing code doesn't broaden the asker's understanding of why they were wrong. Elaborate. Annotate. Goulstem 8144 — 8y
0
I said I added a wait.. What I get for trying to help people :( Im_Kritz 334 — 8y

Answer this question