MouseButton1Click firing multiple times?

I am attempting to make a inventory system:

local function InsertMaterial()
	
	for i, m in pairs(Inventory:GetChildren()) do
		
		if m:IsA("TextButton") then
			
		m.MouseButton1Click:Connect(function()

           -- do stuff

end)
   end
 end
end

Inventory.ChildAdded:Connect(InsertMaterial)

Here, I have a for loop that iterates through all the text buttons in a frame and connects them to an event.

Each time a new item is added to the inventory, a ChildAdded event fires and calls the function that iterates through all the text buttons once again (because the item will be a text button) to pickup on the new item and connect MouseButton1Click to that as well.

However, for some reason the mouse click event fires multiple times when I click on one of the new items (text buttons) added to the inventory and I can’t seem to figure why. It would be greatly appreciated if anybody could tell me why this is happening.

Have you tried to put the debounce?

local debounce = false

--once you call the function make the debounce true
if debounce == false then
         debounce = true

    local function InsertMaterial()
	     for i, m in pairs(Inventory:GetChildren()) do
		
		    if m:IsA("TextButton") then
			
		           m.MouseButton1Click:Connect(function()

                              -- do stuff

                           end)
                    end
            end
    end
   wait() --put any cooldown time you wish
   debounce = false
end

This should work. If not, check https://developer.roblox.com/en-us/articles/Debounce

1 Like

You are hooking up events for every child each time a child is added. So essentially, you are hooking up buttons multiple times.

Instead you might want to only hook up the child that is added if it is a text button. This way each button only get’s one MouseButton1Click event connected each.

5 Likes