How can I make this anti hat duplication less hacky?

game.Players.PlayerAdded:Connect(function(player)
	player.CharacterAdded:Connect(function(character)
		local tools = 0
		local hats = 0
		local humanoid = character:FindFirstChild("Humanoid") or character:WaitForChild("Humanoid");
		character.ChildAdded:connect(function(p)
			if p:IsA("Accessory") or p:IsA("Accoutrement") then
				hats = hats + 1
				if hats > 10 then
					p:Destroy()
				end
			elseif p:IsA("Tool") then
				tools = tools + 1
				if tools > 1 then
					p:Destroy()
				end
			end
		end)
		character.DescendantRemoving:connect(function(p)
			if p:IsA("Accessory") or p:IsA("Accoutrement") then
				hats = hats - 1
			elseif p:IsA("Tool") then
				tools = tools - 1
			end
		end)
    end)
end)

Right now, having a number value with the amount of hats the player has and changing it depending on DescendantRemoving and ChildAdded seems a bit hacky, what would be another way I could do this?

1 Like

You could also just check if the name of an accesoire gets duplicated in the player.

Hi there,

I would rather use arrays instead of just numbers for the hats, such as the following:

game.Players.PlayerAdded:Connect(function(player)
player.CharacterAdded:Connect(function(character)
	local tools = 0
	local hats = {count = 0};
	local humanoid = character:FindFirstChild("Humanoid") or character:WaitForChild("Humanoid");
	character.ChildAdded:connect(function(p)
		if p:IsA("Accessory") or p:IsA("Accoutrement") then
        if hats[p.Name] or hats.count > 10 then
           p:Destroy();
        else 
           hats[p.Name] = true;             
	       hats.count = hats.count + 1; 
        end
		elseif p:IsA("Tool") then
			tools = tools + 1
			if tools > 1 then
				p:Destroy()
			end
		end
	end)
	character.DescendantRemoving:connect(function(p)
		if p:IsA("Accessory") or p:IsA("Accoutrement") then
			hats[p.Name] = nil;
            hats.count = hats.count -1 
		elseif p:IsA("Tool") then
			tools = tools - 1
		end
	  end)
     end)
end)