How do I make it so only one is put into my inventory?

Hello everyone! I was trying to make a shop system. It’s almost complete except this one bug where i click on the buy button once and it gives me 8 of the same item instead of just one. It also multiplies the price by 8 times. How can i fix this problem? Thank you!

buyButton.MouseButton1Click:Connect(function()
	if tonumber(buyButton:WaitForChild("Amount").Text) <= points.Value then
		for i, item in pairs(items:GetChildren()) do
			if item.Name == name.Text and item:GetAttribute("Category") ~= "Consumable" then
				if table.find(inventory:GetChildren(), item.Name) then
					notenufmuny:Play()
				else
					purchase:Play()
					local purchasedItem = items:FindFirstChild(name.Text):Clone()
					purchasedItem.Parent = inventory
					points.Value -= buyButton:WaitForChild("Amount").Text
				end
			else
				purchase:Play()
				local purchasedItem = items:FindFirstChild(name.Text):Clone()
				purchasedItem.Parent = inventory
				points.Value -= buyButton:WaitForChild("Amount").Text
			end
		end
	else
		notenufmuny:Play()
	end
	buyButton.Size = UDim2.new(0.9, 0, 0.15, 0)
	buyClick:Play()
end)

FYI, the inventory is the localplayer’s backpack, and the items variable is a folder in ReplicatedStorage with all the items.

I would recommend adding break on line 12. This exits the for loop and prevents it from triggering multiple times:

buyButton.MouseButton1Click:Connect(function()
	if tonumber(buyButton:WaitForChild("Amount").Text) <= points.Value then
		for i, item in pairs(items:GetChildren()) do
			if item.Name == name.Text and item:GetAttribute("Category") ~= "Consumable" then
				if table.find(inventory:GetChildren(), item.Name) then
					notenufmuny:Play()
				else
					purchase:Play()
					local purchasedItem = items:FindFirstChild(name.Text):Clone()
					purchasedItem.Parent = inventory
					points.Value -= buyButton:WaitForChild("Amount").Text
					break
				end
			else
				purchase:Play()
				local purchasedItem = items:FindFirstChild(name.Text):Clone()
				purchasedItem.Parent = inventory
				points.Value -= buyButton:WaitForChild("Amount").Text
			end
		end
	else
		notenufmuny:Play()
	end
	buyButton.Size = UDim2.new(0.9, 0, 0.15, 0)
	buyClick:Play()
end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.