Multiple GUI Button Registering

I’m currently looking into doing some GUI stuff and was wondering when it came down to button registering, what’s the most efficient way to do so.

Like say I had n amount of buttons, would the best method be to use a loop to go through each button and see if its registered or not like:

local buttons = {} -- Array of button elements
-- Print the button that was activated
local function register(btn)
    print("Button", btn.Name, "Registered")
end
-- Loop through all the buttons
local function btnRegister()
    for i = 1, #buttons, 1 do
        buttons[i].MouseButton1Click:Connect(register)
    end
end

or would the really messy approach be better:

local b1 = parent.B1
local b2 = parent.B2
local b3 = parent.B3
-- Print the button that was activated
local function register(btn)
     print("Button", btn.Name, "Registered")
end
-- Listen for all buttons
b1.MouseButton1Click:Connect(register)
b2.MouseButton1Click:Connect(register)
b3.MouseButton1Click:Connect(register)

Or is there some other method I’m not aware of for this kind of system, any help would be greatly appreciated

MouseButton1Click does not pass an argument when fired.
It really depends on the case, if you want the buttons to do the same thing, then you can just loop through a table with them and connect the same function to MouseButton1Down.

local buttons = {};
table.insert(buttons, BUTTON_LOCATION);

local registered = {};
for _, x in next, buttons do
	registered[x] = x.MouseButton1Down:Connect(function() --// register button function
		print('Button', x.Name, 'was clicked.');
		registered[x]:Disconnect() --// button no longer works after first click
	end);
end;

Something like this ^

2 Likes