Script to handle an updating table of buttons?

I am attempting to make a GUI that lets you spawn and edit parts. The function for button presses is contained within a singular local script. I want it to return which descendant was clicked.

When a new button is clicked, the function fires multiple times for every descendant in the list (including each button’s 5 children). The more buttons that are created, the more the function fires, and the laggier and messier things get down the line.

after 1 button is created and clicked
image
after 4 buttons are created and one is clicked
image

local ButtonsTable = {}
local ListofButtons = Instance.new("Folder")

ListofButtons.DescendantAdded:Connect(function() -- fires when the player adds a button to the list
-- this fires once for EVERY DESCENDANT, every time its clicked
	for i,v in pairs(ButtonsTable) do
		v.MouseButton1Down:Connect(function(ButtonBeingClicked)
			print("Button was clicked") 
			-- the rest of the code
		end)
	end
end)

I’m not sure how else to optimize an updating table of buttons like this. Are there any other methods instead of DescendantAdded?

1 Like

I personally wouldn’t use a for loop every time you add a button, instead, I would recommend using the descendant value provided with the DescendantAdded event. Then you can just tie the click function to that.

ListofButtons.DescendantAdded:Connect(function(descendant)
     descendant.MouseButton1Down:Connect(function()
          print("Button was clicked")
     end)
end)

Apologies if this has some small spelling error, it was written outside of studio : )

1 Like

This worked, thank you so much!! It seems I was getting caught up in making sure the descendants were limited to text buttons and image buttons that I didn’t realize I could use descendant:IsA() before the function, which now makes the script work as intended.

2 Likes

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