Initalize every button at Runtime, keep track of which buttons are being clicked, make sure you add a debounce. Once you are keeping track of the last 2 buttons that were clicked, then you do not to iterate through all of them
I ran into a similar problem with my game and found a way to have as many “buttons” as you want with just one connection. The way it works is by using UserInputService to detect when the mouse is clicked, and then seeing if any of the buttons are in the same position as the mouse when it was clicked.
local UserInputService = game:GetService('UserInputService')
local GuiService = game:GetService('GuiService')
local function GetGuiObjectsAtPosition(input : InputObject)
local offset = GuiService:GetGuiInset()
local pos = Vector2.new(input.Position.X, input.Position.Y)
return player.PlayerGui:GetGuiObjectsAtPosition(pos.X, pos.Y)
end
UserInputService.InputBegan:Connect(function(input)
if (input.UserInputType == Enum.UserInputType.MouseButton1) or (input.UserInputType == Enum.UserInputType.Touch) then
for _, gui in pairs(GetGuiObjectsAtPosition(input)) do
-- Check if gui is one of the buttons
-- Rest of the code here
end
end
end)
local buttonfol = nil --aqui va donde estan los botones
for i ,button in pairs(buttonfol:GetChildren()) do
if button:IsA("ImageButton") then
button.MouseButton1Click:Connect(function()
-- aqui el codigo
end)
end
end
I have edited this a tiny bit, while maintaining everything you have originally, and I have gotten it to work perfectly. I added a debounce and everything runs smoothly. Thank you so much! Additionally, I am going to make it to where it makes sure it’s parent is in the directory I am looking for, so it doesn’t interfere with any other ImageButtons
this is kind of a bloated way to do it. Like ian said below, you can just use a for loop and check if each button is clicked instead of having to check positions. It does the exact same thing and the code is shorter.