What's wrong with my hat deletion script?

I am trying to make a script that delete’s a player’s hats when a button is clicked. This script is a local script within a text button ⇓

local player = game.Players.LocalPlayer
local char = player.Character or player.CharacterAdded()

script.Parent.MouseButton1Click:Connect(function()
	for i, v in pairs(char) do
		if v.ClassName == "Accessory" then
			v:Destroy()
		end
	end
end)

Thanks for your time!

Change this to player.CharacterAdded:Wait() as you’re waiting for the CharacterAdded event of the player to fire.

Change this to for i,v in pairs(char:GetChildren()) do as pairs() expects a table.

It’s also important to know that players.LocalPlayer doesn’t exist on the server, or if your script is on the client (it should be as you’re handling UI objects), it won’t show to other users.

FYI: RemoveAccessories. Works if you can get a Humanoid.

That being said, you do need a RemoteEvent here if you’re expecting that other players should also be able to see that the player removed their hats. If it’s just a LocalScript then only the player who clicked the button will be able to see their hats being removed after the click.

I see, thanks! How should I do that with a remote event?

LocalScript calls FireServer on the RemoteEvent when the button is clicked. Server uses OnServerEvent to consume a fire request from the client and removes the accessories.

These are not full code samples so you’re expected to do some work to fill in blanks yourself or only use this as reference code. It will not work just copy-pasted into a script and I can’t offer any fixes if no attempts were made to integrate/learn from the code samples below.

-- LocalScript
MouseButton1Click:Connect(function ()
    RemoteEvent:FireServer()
end)

-- Script (should be in ServerScriptService ideally)
RemoteEvent.OnServerEvent:Connect(function (player)
    local character = player.Character
    if not character then return end -- Do nothing if no character

    local humanoid = character:FindFirstChildOfClass("Humanoid")
    if not humanoid then return end -- Do nothing if no humanoid

    humanoid:RemoveAccessories()
end)

Thank you so much! I used the code as reference and it worked perfectly :slight_smile: