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

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

Asked by 5 years ago

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

Log in to vote
2
Answered by
mattscy 3725 Moderation Voter Community Moderator
5 years ago

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.

0
Thank you! I also found out that this works! Lostisdead 5 — 5y
0
You should have one function definition and then use that function so you don't make a new function each time. hiimgoodpack 2009 — 5y
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? mattscy 3725 — 5y
Ad
Log in to vote
2
Answered by
T1mes 230 Moderation Voter
5 years ago

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)
0
thank you! Lostisdead 5 — 5y

Answer this question