How can i apply events to 3 or more textbuttons at once?

I have a Gui that contains a high number of textbuttons.

If i try to use i,v in pairs to get every one of them to have the event then when you click one it will run the script for the number of buttons there is.

I could stick with the basic method of just stacking up the events in a script:

TextButton.Activated:Connect(function()
--gui script
end)

TextButton.Activated:Connect(function()
--gui script
end)

TextButton.Activated:Connect(function()
--gui script
end)

But i want a more effective way to do this.

You can use a GetDescendants/GetChildren loop on the shared ancestor of each button, then check whether each object is a TextButton, like such:

local sharedAncestor = --whatever the shared ancestor of all the buttons is

for _,descendant in pairs(sharedAncestor:GetDescendants()) do
   if descendant:IsA("TextButton") then
      descendant.Activated:Connect(function()
          --gui script
      end)
   end
end

Of course, if the shared ancestor is 2+ tiers away on the hierarchy, make sure to use GetDescendants() otherwise, if they are children of the same object, you can use GetChildren() to avoid looping through unnecessary objects.

Addition: if you want to search for both TextButtons and ImageButtons, you can just check if an object is a GuiButton, which is the superclass of both types of buttons

5 Likes

Why don’t you duplicate the local script into each other?

script.Parent.MouseButton1Click:connect(function()

 ReplicatedStorage.Events.YourFunctionHere:FireServer()

end)

Generally having multiple scripts carrying out the exact same function is bad practice and unnecessary. In this case iterating through the children/descendants of an instance in a loop and then checking if they’re the ones we’re interesting in is a better option.

1 Like

Well my script must be bugged then because for me doing that loop makes so when you click one button it fires all of them, but i made a fresh script that used that loop and it worked
So i will have to fix my script.