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

How can I use MouseButton1Click on children?

Asked by 7 years ago

I want to make something happen when one of several buttons is clicked. All the buttons are text buttons, parented to a frame. The following code gives me an error like this: attempt to index field "MouseButton1Click" (a nil value)

Any help on how to make this work would be appreciated.

local buttons = script.Parent.Frame:GetChildren()

buttons.MouseButton1Click:connect(function()
    print("It works!")
end)
  • I checked the wiki-- MouseButton1Click is a valid event of the TextButton object, so I don't think that's the problem :V

1 answer

Log in to vote
1
Answered by 7 years ago
Edited 7 years ago

GetChildren doesn't change everything

Here's a link to a SH help post about the subject.

Then how do I fix it?

Loop though the table and add the event to each button. This is fairly easy. Example,

local buttons = script.Parent.Frame:GetChildren()

for i,v in pairs(buttons) do
    v.MouseButton1Click:connect(function()
        print("It works!")
    end)
end
on line 3, we make a variable named v for the current button in a table.

If you need more information, try this link about generic for loops like the one we used.

Good Luck!

If I helped, please don't forget to accept my answer.
0
Thank you :D Very well stated answer. It works like a charm! Thanks for the links as well :P imperialstar 110 — 7y
0
No problem :3 User#11440 120 — 7y
Ad

Answer this question