MouseButton click fires multiple times for a single item

So basically I am making a backpack system and dropping items has been a real challenge, every time mouse button is up the script piece for mouse button being up runs for as many item frames in backpack.I saw a post talking about how you should link each mouse button click to the child added when using child added. Left me confused, thought maybe Id mention it. Would appreciate if anyone could help me understand what is going on here thanks.

Local Script piece that contains everything you should need to see:

InventoryGUI.ItemOrder.ChildAdded:Connect(function()
	for _,ImageB in pairs(InventoryGUI.ItemOrder:GetDescendants()) do
		print("DEF")
		if ImageB:IsA("ImageButton") then
			ImageB.MouseButton2Up:Connect(function()
				local DVal = PlayerInventory:FindFirstChild(ImageB.Parent.Name)
				if DVal.Value <= 0 then
					return
				end
				local DTex = ImageB.Parent.ItemQuantity.Text
				local IDrop = ImageB.Parent.Name
				local MoveItem = nil
				if IDrop == "9mm bullet" then
					MoveItem = plerr.Backpack:WaitForChild("9mm BulletH")
				elseif IDrop == "45 ACP" then
					MoveItem = plerr.Backpack:WaitForChild("45 ACPH")
				end
				MoveItem.Parent = game.Workspace
				print(MoveItem.Name)
				MoveItem.RHolder.CFrame = HumanoidRoot.CFrame + HumanoidRoot.CFrame.LookVector * 3.5 + Vector3.new(0, 2, 0)
				game.ReplicatedStorage.InventoryDropPickUp:FireServer(DVal, -1)
				print("RAN")
				DTex = DVal.Value
			end)
		end
	end
end)

It’s probably because anytime a child is added, instead of checking that child you’re looping through everything and making another MouseButton2Up for the ones that already have it.

What you could do is put that in pairs loop as its own thing, and do the same for the childadded.

Here’s what I mean

local function checkChild(button)
	if button:IsA("ImageButton") then
		button.MouseButton2Up:Connect(function()
			local DVal = PlayerInventory:FindFirstChild(button.Parent.Name)
			if DVal.Value <= 0 then
				return
			end
			local DTex = button.Parent.ItemQuantity.Text
			local IDrop = button.Parent.Name
			local MoveItem = nil
			if IDrop == "9mm bullet" then
				MoveItem = plerr.Backpack:WaitForChild("9mm BulletH")
			elseif IDrop == "45 ACP" then
				MoveItem = plerr.Backpack:WaitForChild("45 ACPH")
			end
			MoveItem.Parent = game.Workspace
			print(MoveItem.Name)
			MoveItem.RHolder.CFrame = HumanoidRoot.CFrame + HumanoidRoot.CFrame.LookVector * 3.5 + Vector3.new(0, 2, 0)
			game.ReplicatedStorage.InventoryDropPickUp:FireServer(DVal, -1)
			print("RAN")
			DTex = DVal.Value
		end)
	end
end


InventoryGUI.ItemOrder.ChildAdded:Connect(function(child)
	checkChild(child)
end)

for _,ImageB in pairs(InventoryGUI.ItemOrder:GetDescendants()) do
	print("DEF")
	checkChild(ImageB)
end

At first it’ll do a loop and set the event for the ImageButtons, but then when a child is added, it checks only that if it’s an imagebutton and if it is, give it the event

2 Likes