I was wondering if it is better to check if a series of UI buttons were pressed seperately like this:
Button.MouseButton1Click:Connect(function()
--do what I need to do
end)
or check them all with a i, v loop like this:
for i, v in pairs(buttons) do --buttons is classified earlier in my script which isn't shown here.
v.MouseButton1Click:Connect(function()
--do what I need to do
end)
end
I’m not completely sure on which one to pick. I am fine with having to check them both seperately even if it may be quite a few more lines (I have to do this for about 5 UI buttons) but I am worrying about unnecessary lag that may be caused if I use the loop.
Button.MouseButton1Click:Connect(function()
--do what I need to do
end)
Because if you are doing a different button which is different to others then there is no point because if you want it to function differently than others, then in a loop, it won’t work as you want to.
But if you are doing a button that has the same function, then do the loop. However, I would recommend to do the following:
for _,v in pairs(script.Parent:GetChildren()) do
if v:IsA("TextButton") then
v.MouseButton1Click:Connect(function()
--insert code here
end)
end
end
But it is recommended to do separately because you can just put it in a function of whats needing to do and then paste the function in the code bit and copy and paste.
local frame = script.Parent
local function openFrame()
frame.Visible = true
end
for _, button in ipairs(frame:GetChildren()) do
if button:IsA("TextButton") or button:IsA("ImageButton") then
button.MouseButton1Click:Connect(openFrame)
end
end
This is just an example script but this is how you’d optimise your script, currently for each button you’re defining an entirely unique (separate) anonymous function value (which contains the same code as the others) and connecting it to the “MouseButton1Click” event of each button. Instead, you should define the function once outside of the loop and then connect this single callback function to the “MouseButton1Click” event of every TextButton/ImageButton instance.