How can I use one event connection for multiple objects?

So I’ve got this menu with a couple for textButtons, I feel like it’d be impractical to write an event for literally every button.
Instead of doing something like:

textButton.MouseButton1Down:Connect(exampleFunction)

textButton.MouseButton1Down:Connect(exampleFunction)

textButton.MouseButton1Down:Connect(exampleFunction)

textButton.MouseButton1Down:Connect(exampleFunction) 
--etc lol

How can I take one input, and apply it to multiple buttons to check for if they were clicked or not?

Some background info:

  • The script creates a new button, and up to 30 buttons can exist at once.
  • That being said, the actual amount of buttons isn’t definite.
  • They’re all text buttons
  • They all have the same parent (a scrolling frame)
  • They’re all the same size
  • They have different positions

Any ideas?

You can just iterate through the children, and then Establish a connection that way.

for _, child in ipairs(frame:GetChildren()) do
    if child:IsA("GuiButton") then
        child.MouseButton1Down:Connect(fn)
    end
end
3 Likes

just loop through the buttons with a for loop like this:
for index,button in pairs(ScrollingFrame:GetChildren())do
---mouse event here
end

1 Like

I’d suggest creating a function so you can catch any new buttons added and run this function through the buttons that do exist. This way, you cover for an undefined amount of buttons if they aren’t all added at a single time. It also ticks off the rest of your use cases.

local function exampleFunction(parameters)
    something(parameters)
end

scrollingFrame.ChildAdded:Connect(function (child)
    if child:IsA("TextButton") then
        child.MouseButton1Down:Connect(exampleFunction)
    end
end)

for _, button in pairs(scrollingFrame:GetChildren()) do
    if button:IsA("TextButton") then
        button.MouseButton1Down:Connect(exampleFunction)
    end
end
9 Likes

I actually had this set up before but couldn’t figure out why It wasn’t registering for new buttons. :v:
Thanks.

Funny enough, this tells the in pairs loop to run even tough the event is inside of it. I’ve been using this for quite a while and still can’t figure out the logic behind it xd