Function disconnecting problem

Hi everyone I’m currently doing Multi delete system (This is my first time trying to do)
so basically I’m using a remote event to activate and deactivate my multi delete system and checking which ImageButton has been pressed then try to find Item in Inventory with the same name as ImageButton but I’m facing a problem that everytime I tried to deactivate and disconnect from function it doesn’t seem to be disconnected, Idk If I explain clearly or not.

The problem is everytime I run the function for second time (to disconnect) It doesn’t seem to be disconnect and It will started to run multiple time
I have been trying to figure out this problem for a day now so I appreciate every help and suggestion

here is my shortcut of full script that’s have the same problem

local TestEvent = game.ReplicatedStorage.TestEvent

local connection 

local Already_Run = false

local function Example(player)
    if not Already_Run then
        Already_Run = true
        print("Function Start Running")
        
        for i, Template in ipairs(player.PlayerGui:WaitForChild("ScreenGui").Frame:GetChildren()) do
            if Template:IsA("ImageButton") then
                local function MouseClick()
                    print("ImageButton Click")
                end
                
                connection = Template.MouseButton1Click:Connect(MouseClick)
            end
        end
    elseif Already_Run then
        Already_Run = false
        print("Function Stopping")
        if connection then
            print("Disconnected")
            connection:Disconnect()
        end
    end
end

TestEvent.OnServerEvent:Connect(Example)
1 Like

Upon closer inspection, I noticed that connection was being set up multiple times, how about using table.insert() to add to the connection table, and then iterating through the connections to disconnect all of them.

Ignore the below as I was under the impression that connection was a single connection. Still going to keep as it might be useful, but not in this case. Expand if you want an answer that I made without fully looking into it.

Expand

From the sound of it, you’re not properly disconnecting the connection for some reason. How about instead of checking Already_Run, check if the connection exists, and disconnect it at the start of the function to prevent a memory leak? This could also replace the Already_Run variable entirely if done correctly.

Alternatively, if you’re trying to disconnect multiple connections at once, Quenty’s Maid class might be the solution for you.

2 Likes

It’s worked! Thank you so much