New templates keep getting created

This script makes it so that every time a player opens their inventory it creates a template for each item in their inventory. But if you spam the inventory button there is only one item in their inventory but it keeps making more templates how could I check and stop this from happening?

local Player = game.Players.LocalPlayer
local Inventory = Player:WaitForChild("Inventory")
local motherboardFrame = Player.PlayerGui.WorkshopGui.MotherboardFrame.ScrollingFrame
local coolerFrame = Player.PlayerGui.WorkshopGui.CoolerFrame.ScrollingFrame
local cpuFrame = Player.PlayerGui.WorkshopGui.CpuFrame.ScrollingFrame
local gpuFrame = Player.PlayerGui.WorkshopGui.GpuFrame.ScrollingFrame
local powerSupplyFrame = Player.PlayerGui.WorkshopGui.PowerSupplyFrame.ScrollingFrame
local ramFrame = Player.PlayerGui.WorkshopGui.RamFrame.ScrollingFrame
local storageFrame = Player.PlayerGui.WorkshopGui.StorageFrame.ScrollingFrame
local template = Player.PlayerGui.WorkshopGui.Template
local InventoryButton = Player.PlayerGui:WaitForChild("WorkshopButtons").Inventory
local ItemParenting = {
	Motherboard = motherboardFrame,
	Cooler = coolerFrame,
	Cpu = cpuFrame,
	Gpu = gpuFrame,
	PowerSupply = powerSupplyFrame,
	Ram = ramFrame,
	Storage = storageFrame
}

InventoryButton.MouseButton1Click:Connect(function(player)
	for _, item in pairs(Inventory:GetChildren()) do
		local newTemplate = template:Clone()
		newTemplate.Name = item.Name
		newTemplate.ObjectName.Text = item.Name
		newTemplate.Visible = true
		
		local Item69
		local Item420
		
		for name, parent in pairs(ItemParenting) do
			if string.match(item.Name, name) then
				newTemplate.Parent = parent
				Item69 = name
				Item420 = parent
				break
			end
		end

		newTemplate.MouseButton1Click:Connect(function()
			local Check = game.ReplicatedStorage.Inventory:InvokeServer(Player, item.Name, Item69)
			if Check == true then
				Player.Inventory[item.Name]:Destroy()
				Player.PlayerGui.WorkshopGui[Item420.Parent.Name].ScrollingFrame[item.Name]:Destroy()
				Player.PlayerGui.WorkshopGui.Enabled = false
			end
		end)
	end
end)
1 Like