Search for an item with a word in the name

I’m trying to make a hat remover, but some of the hats aren’t set as accessories. All of the hats are named “(Something) Hat”. Is there any way to search for models that have the word “Hat” in them and then destroy them? (Sorry if I’m kind of asking for a script, but I’d have no idea how to go about this)

1 Like

Theres actually a handly variable called ClassName which is a variable that tells you what type of object the item is

You can use

for i,v in pairs(Character:GetChildren()) do
    if v.ClassName == "Accessory" do
        v:Destroy()
    end
end

This will look at all the children in Player and will delete every accessory in it

I’m trying to make a hat remover, but some of the hats aren’t set as accessories.

I think you misread the question. The hats are a model, not an accessory as they are custom. Thanks for trying though.

UPDATE: string.find works much better:

Put that in the for loop from above, and you’re golden:

for i,v in ipairs(Character:GetChildren()) do
    if string.find(v.Name, "Hat") then
        v:Destroy()
    end
end
1 Like

Thanks. I also found another way while I was testing. (A bit longer, but works the same)

for i,v in pairs(player.Character:GetChildren()) do
			local name = v.Name
			local split = name:split(' ')
			if split[2] == "Hat" then
				v:Destroy()
			end
		end

Wouldn’t string.find() be easier?

Yes, yes it definitely would…

This simple implementation would also search for objects that end with “ Hat”:

for i,v in ipairs(Character:GetChildren()) do
  if string.match(v.Name, " Hat$") then
    v:Destroy()
  end
end

Just need to make sure there are no objects that would be false positives, like “Hatchet” or something.

If everything has a space before it, you could search for “ Hat”