Disconnecting an Anonymous Function (listener)

I know this probably has a very simple answer, (no previous posts helped)

image

But when you connect an event (Clicked ) to a function like for example:

local TextButton = script.Parent
local player = game:GetService("Players").LocalPlayer
TextButton.MouseButton1Click:Connect(
    function(player)
        print(player.Name)
    end
)

when do you use Disconnect then? as it says without disconnecting the function, it will keep listening for .Clicked

Not to mention, the code above gives the output “attempt to index nil with player”

Or does the function disconnect it self when not called ?

Thanks for your help //

5 Likes

You need to define the event before you’re able to disconnect it. Like this:

local Mouse1ClickEvent
Mouse1ClickEvent = TextButton.MouseButton1Click:Connect(function()
    print("Clicked!")
    Mouse1ClickEvent:Disconnect()
end)

To answer why the event was erroring when calling the print, MouseButton1Click does not return any arguments. That’s only for ClickDetectors. GuiButton objects can only be clicked by clients, so there’s no point in having a player argument.

5 Likes

But my question is ;
Is it really important to do this? Since it is an anonymous function wont it disconnect it self after end?
And if so , will I have to change all my code to disconnect the function?

1 Like

The client would still be listening for that specific event, which just causes it to use more resources than necessary (as well as potential memory leaks because it isn’t being discarded). For the sake using less memory, it’s best that you do utilize the Disconnect function.

You can’t disconnect a function, but rather the you can disconnect the event. When you disconnect the event, it will stop listening and calling the anonymous function you stated.

1 Like

For the second part of that question, not necessarily. All you have to add is just a few more lines of code to define the event to then disconnect it.

Connecting and disconnecting are one-time things. You shouldn’t disconnect a function from an event after it gets fired and then connect it again, that doesn’t make sense. You connect a function to an event as soon as you need to start listening for an action (here: user input) and disconnect once you’re certain it’s gonna be a considerable amount of time until the connection is needed again, but you aren’t destroying the object that supplies the event.

If you have a TextButton as a (semi-)permanent part of UI and never destroy it, it is usually not necessary or advised to ever disconnect the function from the event, unless you specifically want to (as provided by above example: only listening to an event call once).

1 Like

So what you basically mean by that is that I shouldn’t disconnect the event after being called , because the event that is connected to the function will automatically be stopped being called for after end) ?

And so in other places where events are being fired upon an event (clicked) that connects the Clicked event to the function which fires the other event, there I should disconnect them, because new connections for example would need to be made and disconnected every time right?

Yes. Disconnecting from an event means you will stop listening to the event, it doesn’t mean that your function will stop running. A function will have nothing to do after reaching the end definition and therefore stop. The “running function” isn’t kept in memory, only the connection (when event, do function) which you can usually keep (because you will usually need to use it more than a few times).

No. The event does not ‘stop’ automatically. Once you connect a Mousebutton1Click event, it kinda ‘listens’ until it receives a signal that, yes the button has been clicked. So, Roblox uses resources to ‘listen’ to event. But disconnecting it stops Roblox from ‘listening’ thus doesn’t use resources.

However, disconnecting it doesn’t mean that the function will not run again. It only means that Roblox will stop using resources until the event is connected again thus preventing memory leaks.

Sorry for long paragraphs btw :wink:

For a simplification of what it means to disconnect an event from a function, you cut the “wire”(connection) leading from the input(event) to the output(function).

Usage areas of Connection:Disconnect() are such as acting like a debounce.

3 Likes

But that is exactly what Disconnect does and is for? Once you call Disconnect on an event connection, the corresponding function will not be called again the next (and following) times the event fires.

And Disconnecting everywhere an event that is called for
(given the button is going to be clicked several times)
will result in the button not producing any outcome , is that correct then ?

Sorry I put the sentence in the wrong format.
Hope u still get what i was tryin to say

Ps; I type really fast :stuck_out_tongue:

You can find that function from the object of RBXScriptConnection.


@XxELECTROFUSIONxX
The input will still work, but the connection is severed between, thus resulting no output. Let’s say you have multiple connections on one, and disconnect one. Only the disconnected will stop sending signals to its designated output and others will function without any additional issues.

1 Like

Well can’t we use Coroutines to suspend a function from being called?
Like I came up with this script which works, but don’t know whether it can cause memory/data leakage or something

local button = script.Parent
   button.MouseButton1Click:Connect(coroutine.wrap(function()
	     print("clicked")
end))

but the coroutine dies immediately , thus working only once

1 Like

That’s an odd use of coroutines. However, the connection still exists and may cause memory leak.

1 Like

Well disconnect works More than 1 time so it’s more efficient if you have events that do not need constant ‘listening’

what does it depend on then if not at nothing at all, I mean what I get from what @emojipasta and @Operatik said, disconnect is mainly used in places where you can ‘sever’ the connection , that is where people won’t be using it or the event wont be called that often.
So it is not necessary at places, such as in a Gui where players would click it constantly , i.e to buy things from an in-game shop.

But what happens if you use that in a lot of places (9-20) gui buttons , will it keep listening for the event for every single button , hence causing memory leakage ?

Listening to a lot of events at once doesn’t instantly cause any issues. You’re safe to make hundreds of permanent event connections for your game.
It usually gets problematic when you dynamically create a large, indefinite amount of Instances and connect to their events dynamically as well. Picture this situation: You retrieve thousands of items from a text-format catalog (like a table, JSON file etc.) and create a new set of event connections for each one of the items (“see more details”, “purchase”, etc.). The user may refresh the catalog to re-create those thousands of buttons. Here’s where it (in theory) gets problematic. You would need to disconnect each connection again for a refresh.
However, this isn’t actually a problem, because Roblox automatically disconnects all event connections when Destroying instances. It’s just an example.

A better example: Every time a player chooses to spawn into the world from a main menu, you connect a few looping events (such as movement, camera translation, user input). In this case, you should disconnect all events after the player chooses to go back to the main menu. The events aren’t automatically disconnected and since the player can thereotically respawn an infinite amount of times, you would create an infinite amount of connections, which causes the problems addressed before.

2 Likes