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

How to create a listener that will fire on a variable amount of instances?

Hi all,

What I'm attempting to do is connect a function to an event which will fire on different TextButtons which may be deleted for added at any time. The code that needs to be executed will remain constant however the instance on which the function will fire the event will change. Below I have made a quite frankly mediocre attempt, however I am hoping you guys have a bright idea on how to do this.

function OnClick()
	-- relevant code.
end

sp.ChildAdded:connect(function(child)
	child.TextButton.MouseButton1Click:connect(OnClick)
end)

sp.ChildRemoved:connect(function(child)
	OnClick:Disconnect()
end)

Thanks in advance.

1 answer

✓ Accepted answer

You don't need to disconnect anything. If the objects go away, they won't fire the event anymore (ROBLOX should automatically clean up the loose ends in memory).

The first 7 lines will work exactly as you'd expect. Clicking any new child that has a TextButton will fire OnClick.

Note that they will all do the exact same thing, and you can't differentiate which button was pressed. If you want to know that, you need to add extra:

function onClick(whichButton)

end

script.Parent.ChildAdded:connect(child)
	if child:IsA("TextButton") then
		child.MouseButton1Down:connect(function() onClick(child) end)
	end
end

1 comment

0

Thanks pal

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