Hey, I was trying to mess around with connections today and today I tried to disconnect a connection inside the connection itself, but it still won’t disconnect
I tried connection:Disconnect() and connection = nil, but it will still print “testing”
Theres many different methods you could use to disconnect functions
In the case of the code you shown, a simple way you could disconnect would be
humanoid.Jumping:Connect(function()
local cn
cn = humanoid.StateChanged:Connect(function)
--your code here
cn:Disconnect()
end)
end)
If you had alot of connections and wanted to disconnect them in bulk in an efficient manor you could do something like this, using a table
local conn = {}
--if your script is in a serverscript this + the functions will need to be in a PlayerAdded event (so you can get Player)
conn[Player] = {}
conn[Player][#conn[Player] + 1] = humanoid.StateChanged:Connect(function)
--your code here
end)
--then use this loop to disconnect all of them
--if this is used in a server script slap it in a PlayerRemoving event (outside of the PlayerAdded event)
for i, connect in pairs(conn[Player]) do
connect:Disconnect()
conn[Player][i] = nil
if #conn[Player] <= 0 then
conn[Player] = nil
end
end
Of course if it was only a client sided script you can just store the functions in the table without the player parts.
Here is an example of how to disconnect a connection inside the connection itself:
local event = game.ReplicatedStorage.MyEvent
local connection
connection = event.OnServerEvent:Connect(function(player)
print(player.Name .. " has triggered the event.")
-- Check some condition to determine if the connection should be disconnected
if someCondition then
connection:Disconnect() -- Disconnect the connection
end
end)
In this example, a connection is established between the MyEvent event and a function that is triggered when the event is fired on the server. Inside the function, a condition is checked to determine if the connection should be disconnected. If the condition is met, the Disconnect() method is called on the connection object to disconnect the connection.
By using the Disconnect() method inside the connection itself, you can easily disconnect the connection based on certain conditions or criteria.
You want ‘testing’ to not print? Disconnecting the event only stops the event from firing again, it won’t stop the event currently running. You can add return like so
If the connection is meant to immediately disconnect after a single event with no exceptions, you can just use :Once() instead.
event.OnServerEvent:Once(function(player)
--do stuff
end)
--automatically disconnected and don't have to worry about memory leaks since the connection is anonymous