How to delete hats off a character?

(Yes, I’ve made another post. I’m getting too carried away with devforum! I will be asleep once I make this post so in the morning I’ll respond to all of them :slight_smile: )

My issue is that I cannot remove hats from a character and I can’t figure it out. It’s to stop collision with other hats for a mask.

Script:

character = tool.Parent
	local hats = character:GetChildren("HatAccessory")
	hats:Destroy()

Error:

 Players.squaredsnow.Backpack.Troll Tool.Activate:7: attempt to call a nil value

I don’t know a lot about accessories. If anyone could tell me, that would be great.

Hey me again. All you gotta do really is just make the script this

local tool = script.Parent
local death = tool:WaitForChild("Death")

death.OnServerEvent:Connect(function(player, character)
	character = tool.Parent
	character.Humanoid.Health = character.Humanoid.Health - 50
	for _, Hat in pairs(character:GetChildren()) do
		if Hat:IsA('Accessory') then
			Hat:Destroy()
		end
	end
end)

If it doesnt work i can help

2 Likes
for _, Object in pairs(Character:GetChildren()) do
	if Object:IsA("Accessory") and Object.AccessoryType == Enum.AccessoryType.Hat then
		Object:Destroy()
	end
end
2 Likes

Thanks for helping me on 2 posts :smiley:

You don’t even need a loop for this, Roblox’s API has an instance method specifically purposed for the removal of a player’s character’s worn accessories.

local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")

task.wait(5)
Humanoid:RemoveAccessories()

https://developer.roblox.com/en-us/api-reference/function/Humanoid/RemoveAccessories

What does task.wait do?

Also the :RemoveAccessories() function looks really useful.

task.wait() is a newer version of wait() that resumes a thread after it has reached the desired time you applied. They are basically the same thing.

So stops the entire script then resumes after it finishes?

Yes, it functions the same way wait() does but a different name and a slightly different function. You can research more about task library here.