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 7 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?

local frame = script.Parent

--script errors at the print function because button never actually exists
function buttonClicked(button)
    print(button.Name .. " was clicked!")
end

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(buttonClicked)

    end
end

1 answer

Log in to vote
1
Answered by 7 years ago
Edited 7 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:

local frame = script.Parent

--script errors at the print function because button never actually exists
function buttonClicked(button)
    print(button.Name .. " was clicked!")
end

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

-- This makes it so once the button is clicked, it will call
    -- 'buttonClicked', while also passing the argument 'v'
    -- to it, which is the button.

    v.MouseButton1Click:connect(function()
        buttonClicked(v)
end)

    end
end

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

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

Answer this question