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

How do i subscribe all of buttons mouseclick1 event to the same function?

I know how to make it so a single button's mouseclick event connects to a function, but what if I want for example 10 buttons connect to the same function when clicked?

2 answers

You are able to use a loop to iterate through the buttons. For example, if the script was inside a model with all the parts you want to detect clicks for, you could do something like this:

for _,Part in pairs(script.Parent:GetChildren()) do
	if Part:IsA("BasePart") then
	local CD = Instance.new("ClickDetector")
	CD.Parent = Part
	CD.MouseClick:Connect(function(Plr)
		print(Part.Name .. " was clicked by " .. Plr.Name)
	end)
end

This would go through each part in the model, creating a ClickDetector for each and listening for when each of them is clicked.

3 comments

0

Thank you! I also found out that this works!

0

You should have one function definition and then use that function so you don't make a new function each time.

0

Hmm, never though about it that way. Except how would you get the part that was clicked, since it would be a separate scope?

You can create a function and call upon it every time the event is fired like so:

function wow()
	print'wow'
end

b1.MouseButton1Click:Connect(wow)
b2.MouseButton1Click:Connect(wow)
b3.MouseButton1Click:Connect(wow)

1 comment

0

thank you!

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