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

How can I use MouseButton1Click on children?

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

✓ Accepted answer

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.

2 comments

0

Thank you :D Very well stated answer. It works like a charm! Thanks for the links as well :P

0

No problem :3

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