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

How would I make this simple script work?

Asked by
xPolarium 1388 Moderation Voter
9 years ago

Please make your question title relevant to your question content. It should be a one-sentence summary in question form.

I've been looking into in pairs, and I have this problem with this simple script. What I want it to do is, remove all the hats a player would have when he spawns. I thought using game.Players.PlayerAdded:connect(function() would help since I want it when the player joins but of course if the player dies I don't want them to have the hats on. Additionally, this script was working when "Hat" was set to "BasePart" before. I have no idea why the hats don't want to get removed even though the player's parts did.

This is in a local script in startpack.

--[[]]--
local player = game.Players.LocalPlayer.Character

--Main

function RemoveBody()
    for i, v in pairs(player:GetChildren()) do
        if v:IsA("Hat") then
            v:Destroy()
            wait(.1)

        end
    end
end

RemoveBody()
0
starterpack* xPolarium 1388 — 9y

1 answer

Log in to vote
4
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

The problem is likely that the Character hasn't loaded by the time this script has.

There's more problems with that, since the hats won't necessarily be there the moment the player is.

First, we need to get a good reference to the character.

One of the following two will work (I prefer the first for being so cute)

local player = game.Players.LocalPlayer
locla character = player.Character or player.CharacterAdded:wait()

-- OR --
local player = game.Players.LocalPlayer
repeat
    wait()
until player.Character
local character = player.Character

Now we can try to remove hats:

function destroyHat(hat)
    if hat:IsA("Hat") then
        hat:Destroy()
    end
end

function removeHats( model )
    for _, child in pairs(model:GetChildren()) do
        removeHat( child )
    end
end

removeHats( character )

We should also probably check any new additions to the player after this point in case new hats are added:

character.ChildAdded:connect( destroyHat )
0
Thanks. I was actually keeping in mind that it's probably not working because the character hasn't loaded in. I just didn't know how to get around that. Thanks and upvoted c: xPolarium 1388 — 9y
Ad

Answer this question