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

Connect group function to individual object?

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

✓ Accepted answer

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.

1 comment

0

your help has been indispensable, thank you!

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