Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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

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))
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!

This discussion is preserved as it was. New answers, comments, and votes are closed.