Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

Detect if ANY button in a table has been clicked?

Asked by 7 years ago

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

Log in to vote
1
Answered by 7 years ago

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.

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 patrline5599 150 — 7y
0
You mean have the function that executes once the event is fired, be somewhere else in the script? ScriptGuider 5640 — 7y
0
I mean I'd like to be able to use the exact button that was clicked as a variable inside of the function. patrline5599 150 — 7y
0
No problem, answered it in your latest question. ScriptGuider 5640 — 7y
0
Yep! Thanks patrline5599 150 — 7y
Ad
Log in to vote
1
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
7 years ago

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
0
Great answer, thanks for your help. patrline5599 150 — 7y

Answer this question