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

Connect group function to individual object?

Asked by 8 years ago

I have a GUI with buttons and a function that fires whenever any of the buttons are clicked. However, the function doesn't seem to be returning any data about the actual particular button that was clicked. Is there a way to make this work?

01local frame = script.Parent
02 
03--script errors at the print function because button never actually exists
04function buttonClicked(button)
05    print(button.Name .. " was clicked!")
06end
07 
08for i,v in pairs(frame:GetChildren()) do
09 
10    -- Let's go ahead and check if the object is a button in the first place
11    if v:IsA("TextButton") or v:IsA("ImageButton") then
12 
13        -- Connect the event to that individual button.
14        v.MouseButton1Click:connect(buttonClicked)
15 
16    end
17end

1 answer

Log in to vote
1
Answered by 8 years ago
Edited 8 years ago

Callbacks

What you're referring to is a callback. This is basically a way to have a function call another function, while passing arguments to the function it's calling. This is extremely useful in a lot of specific cases. Here would be an example in your scenario:

01local frame = script.Parent
02 
03--script errors at the print function because button never actually exists
04function buttonClicked(button)
05    print(button.Name .. " was clicked!")
06end
07 
08for i,v in pairs(frame:GetChildren()) do
09 
10    -- Let's go ahead and check if the object is a button in the first place
11    if v:IsA("TextButton") or v:IsA("ImageButton") then
12 
13-- This makes it so once the button is clicked, it will call
14    -- 'buttonClicked', while also passing the argument 'v'
15    -- to it, which is the button.
View all 22 lines...

Hope this helped, let me know if you have any questions.

0
your help has been indispensable, thank you! patrline5599 150 — 8y
Ad

Answer this question