Is there any way to disconnected function like this?

Hello, Im currently having a question
You can disconnected a function like this:

function Click()
print(“Clicked!”)
Click:Disconnected()
end
script.Parent.ClickDetector.MouseClick:Connect(Click())

but what about this?

script.Parent.ClickDetector.MouseClick:Connect(function()
--there's no function name so how can I disabled it?
end)

Since I don’t wanna rewrite all functions again (i used touch and it making the game lag)
Thanks!

1 Like

No. That’s not how to disconnect a function. Are you trying to say disconnecting a function/callback connected to an event?

Im sorry (im not good at english), but did you mean disconnecting a function?

You cannot disconnect a function. You can disconnect events, not functions.

1 Like

The Connect method returns a connection. So to disconnect you need to capture the connection into a variable then you can use the Disconnect method on the connection

local connection = script.Parent.ClickDetector.MouseClick:Connect(function()
--there's no function name so how can I disabled it?
end)

connection:Disconnect()

When you disconnected a event, it will decrease the lag?

Yes it will, because if you don’t you may hog up untracked memories which will decrease server performance. Also, it’s called disconnect an event, not disconnect a function.

1 Like

Alright! Thank you, this is all I want to know for this topic

function Click()
	print("Clicked!")
	Click:Disconnected()
end

script.Parent.ClickDetector.MouseClick:Connect(Click())

Just to let you know in your original function “Disconnected()” isn’t a valid method and you don’t need to call the callback you’re connecting to the event you just need to reference the callback you’re connecting by name.

script.Parent.ClickDetector.MouseClick:Connect(Click)

You also can’t disconnect a connection before the connection has been made.

2 Likes

Potentially, it certainly keeps memory clean, which is always a good thing and it is a good practice to disconnect events if they are no longer needed. If you have many events then it is possible the difference in performance would be noticed, but it there are only a few connected events running in the game I doubt anyone would notice the difference. It also depends on what is happening when the event is triggered. If it is a long running process then the difference is likely to be more noticable but again if it does little then it is debatable whether the difference would be noticed. You will only know through testing.