Is this a Memory Leak?

Hi, I’m trying to detect for button clicks/taps within a remote event listener.
I’m not sure if this is a memory leak, i’ve tried to figure it out, and now I’m here.
Will the listening for the buttons stack every time, or will it automatically stop after the remote event is done?

Here’s the code:

--FUNCTIONS--
local function Close()
	GUI.Enabled = false
end

local function Purchase()
	PurchaseGate:FireServer()
end

-------------------------------------------------------------------------------
-------------------------------------------------------------------------------

--RUN TIME--
PromptPurchaseGate.OnClientEvent:Connect(function(Area: Object)
	
	GUI.Enabled = true
	
	PurchaseButton.MouseButton1Click:Connect(Purchase)
	PurchaseButton.TouchTap:Connect(Purchase)
	
	CloseButton.MouseButton1Click:Connect(Close)
	CloseButton.TouchTap:Connect(Close)
	
end)

Thanks :happy2:

Yes. Your event listeners will stack. The only cases in which event listeners are automatically disconnected are as follows:

  1. The instance the event is associated with is destroyed.
  2. The script in which the event listener was connected is destroyed.

You need to store the RBXScriptConnection object returned by RBXScriptSignal:Connect in an upvalue. In your event listener, first check for the upvalue’s tangibility and disconnect any previously stored connections, then store the new ones

1 Like

Could you edit the script to reflect these changes? Thanks, never really did this before

local purchaseConnection
local closeConnection
local function onPromptPurchaseGate(gate: Instance)
    if purchaseConnection and closeConnection then
        purchaseConnection:Disconnect()
        closeConnection:Disconnect()
    end

    Gui.Enabled = true
    
    purchaseConnection = PurchaseButton.Activated:Connect(purchase)
    closeConnection = CloseButton.Activated:Connect(close)
end

(GuiButton.Activated can respond to both mobile and PC “clicks”)

1 Like

I know this is already solved but I’m pretty sure it wouldn’t have been a memory leak anyway.