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

Hat remover on Player Added?

So, I need to get a hat remover when a player enters a server, but haven't seen to get it working yet. Any tips? My code atm:

local player = game:GetService("Players").LocalPlayer
game.Players.PlayerAdded:connect(function()
	for _, object in pairs(player.Character:GetChildren()) do
		if object:IsA("Hat") then
			object:Destroy()
		end
	end
end)

1 answer

✓ Accepted answer

The character doesn't load instantly, you will need another function to fire when the character is added, doing this also allows you to have them removed each time a player dies. The game.Players.PlayerAdded function is unnecessary as each time any player joins it will try to remove the player's hats. Here's the code you should be using assuming this is a local script:

local player = game.Players.LocalPlayer

player.CharacterAdded:connect(function(char)
	for _,obj in pairs(char:GetChildren()) do
		if obj:IsA("Hat") then
			obj:Destroy()
		end
	end
end)

Instead of having this, you could use a server script in Workspace or ServerScriptService, here's the script you could use for that:

game.Players.PlayerAdded:connect(function(player)
	player.CharacterAdded:connect(function(char)
		for _,obj in pairs(char:GetChildren()) do
			if obj:IsA("Hat") then
				obj:Destroy()
			end
		end
	end)
end)

If this worked for you and/or helped you please vote up and accept this as the answer!

3 comments

0

Hm, in Studio, the hats still appear on the player. Do I have to test live?

0

Try it testing live, I wrote the code on my phone so sorry about the missing )'s on some of the ends. I can't actually test the code because I'm on phone, but when I get on my computer I'll test it.

0

It's alright; I've got the code to work, anyhow. I'll accept the answer, for your help. Thanks!

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