Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Detect if ANY button in a table has been clicked?

I have a GUI and I'm trying to detect if ANY buttons within a table have been clicked, and then fire a function based on that. Is this the right way to go about it? (I feel like it isn't). Thanks for your help in advance!

frame = script.Parent
buttons = {}

-- create buttons table
for _,v in pairs (frame:getChildren()) do
	if v:IsA("ImageButton") then
		table.insert(buttons, v)
	end
end

function buttonClicked(button)

end

--when any button is clicked
buttons.Mouse1ButtonClick:connect(buttonClicked())

2 answers

✓ Accepted answer

Tables

buttons is a table, it doesn't represent a singular object that updates everything inside of it once changed. In fact, you won't even need that table because GetChildren() already returns one for you. You can just iterate all the objects inside GetChildren() with a for loop, and connect a button to an event within that for loop. Here's an example:

local frame = script.Parent

for i,v in pairs(frame:GetChildren()) do
	
	-- Let's go ahead and check if the object is a button in the first place
	if v:IsA("TextButton") or v:IsA("ImageButton") then
		
		-- Connect the event to that individual button.
		v.MouseButton1Click:connect(function()
			print("Button was clicked")
		end)
	
	end
end

This would accomplish what you were describing. Hope this helped, just let me know if you have any questions.

5 comments

0

Hate to bug you again, but am I able to connect the function with the particular BUTTON that was clicked? I want to get data about the particular button whenever the function fires

0

You mean have the function that executes once the event is fired, be somewhere else in the script?

0

I mean I'd like to be able to use the exact button that was clicked as a variable inside of the function.

0

No problem, answered it in your latest question.

0

Yep! Thanks

Well, you're right that you're wrong.

buttons is a list. A list does not have a click event. You want what's inside the list, not the list itself.

Furthermore, buttonClicked() calls the function and is equal to the result of it. In this case, the result is nil. You want to connect the function, not the result of the function. buttonClicked

What you need to do is loop through the table and connect an event to each button like so:

for i, button in ipairs(buttons) do
	button.MouseButton1Click:connect(buttonClicked)
end

1 comment

0

Great answer, thanks for your help.

This discussion is preserved as it was. New answers, comments, and votes are closed.