Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Connect the same function when any one of these buttons are clicked?

Asked by 5 years ago
Edited 5 years ago

Is there a way to make a single function for this:

local var = 0

button1.MouseButton1Down:Connect(function() var = 1 end)

button2.MouseButton1Down:Connect(function() var = 2 end)

button2.MouseButton1Down:Connect(function() var = 3 end)

So when any one of these buttons are clicked, var becomes equal to the number of the button.

local var = 0

button1/button2/button3.MouseButton1Down:Connect(function() var = x end)

(sry can't figure out how to format properly

2 answers

Log in to vote
0
Answered by
yoyyo75 74
5 years ago

yeah you could just pass a function with a parameter in the Connect method:

local var = 0

function sample(x)
    var = x
end
button1.MouseButton1Down:Connect(sample(1))

button2.MouseButton1Down:Connect(sample(2))

button2.MouseButton1Down:Connect(sample(3))
Ad
Log in to vote
0
Answered by
0b1w 13
5 years ago
Edited 5 years ago
local Buttons; -- Define the button(s) parent.

local Var = 0;

local function Add(num)
    Var = Var + num;
end;

for _,button in pairs(Buttons:GetChildren()) do -- Loop through the buttons, add a function, add depending on the buttons name.
    button.MouseButton1Click:Connect(function()
        if (button.Name == "button1") then
            Add(1);
        elseif (button.Name == "button2") then
            Add(2);
        elseif (button.Name == "button3") then
            Add(3);
        end;
    end);
end;

Hope this works for you!

Answer this question