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

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

Asked by
ausmel105 140
8 years ago

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

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

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
0
Thanks pal ausmel105 140 — 8y
Ad

Answer this question