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

Mass MouseButton1Click script?

#Sorry for the bad title

I have over 20 buttons in my main gui, and the way i would think to know if they were click is:

script.Parent.Frame:FindFirstChild(tostring(1)).MouseButton1Click:connect(function()
	--do stuff
end)
script.Parent.Frame:FindFirstChild(tostring(2)).MouseButton1Click:connect(function()
	--do stuff
end)
script.Parent.Frame:FindFirstChild(tostring(3)).MouseButton1Click:connect(function()
	--do stuff
end)
script.Parent.Frame:FindFirstChild(tostring(4)).MouseButton1Click:connect(function()
	--do stuff
end)
script.Parent.Frame:FindFirstChild(tostring(5)).MouseButton1Click:connect(function()
	--do stuff
end)

But this would get annoying to use, because it's so big for just getting the clicked. The question is, how do i get the clicked gui, without doing all these events?

1 answer

✓ Accepted answer

You would have to use a for loop to go through all the children you gather of the Gui with GetChildren(). You would just have to make sure that all elements inside the Frame object are Buttons, otherwise you should have an if then statement to protect your code from error.

for _,v in pairs(script.Parent.Frame:GetChildren()) do
    v.MouseButton1Click:connect(function()
        --Do whatever you want.
        if v.Name == 'Person' then
            print'Person Clicked!'
        elseif v.Name == 'Player' then
            print'Player Clicked!'
        end
    end)
end

The script is going through all objects of the Frame object and will utilize the MouseButton1Click event and connect it to a function. You can get information from the button just by using v in the code. This can help indicate if you hit a button with the name of Person or Player if needed.


######Hopefully this answered your question, if so please hit the accept answer button. If you have any questions, feel free to comment below.

4 comments

0

So v is the item that was clicked?

0

Yes. v is the variable given in the for loop. The for loop is getting an index value and it's coexisting value, being i and v. v is being connected to its own event. However one the for loop is over the only way to identify if a button was hit is when in the event you use that v variable. You can change v to whatever you want it's a variable for value.

0

OK, so the way i see it, when you click anything, in the frame, it'll make the var v equal to the textbutton that was clicked, correct?

0

Essentially yes.

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