Terminating a function with events inside

Hey roblox dev forum, I made a UI and setting up events for all the buttons this is the approach that I did so I can do proper tweenservice whenever event is fired, and such like that. First off if there is a better way to do this, please I am all ears.

I noticed that when I open this UI after closing it, the event functions never get terminated. I have tried using debounces, disconnecting the functions through assigning them to local variables outside the function, but none of this worked. What would be a proper way to approach this problem since when i try to return the main function, it doesnt seem to terminate the event connection functions like I thought they would.

Anything helps thanks.

local function openUI()
	for _,v in pairs(screenGui:GetDescendants())do
		if v:IsA("ImageButton")then
			mouseEnter = v.MouseEnter:Connect(function()
				print("testing1")
			end)
			mouseLeave = v.MouseLeave:Connect(function()
				print("testing2")
			end)
			mouseClick = v.MouseButton1Down:Connect(function()
				print("clicking")
			end)
			testing = runService.Heartbeat:Connect(function()
				print("HELLO")
			end)
		end
	end
end

If you are destroying the UI, hook the gui instance Destroying event, and then call Disconnect on your connections (e.g. mouseEnter).

If the UI is never destroyed, then you should only be calling these Connect functions once, so check that the values (mouseEnter) are nil before setting up the connection.

Thanks YosemiteMe for the respond

The nil check did the job, I hadn’t thought of that so thanks a lot.

Good to know. If you had been destroying the UI, the connections should’ve been automatically disconnected as part of the closure, so this fix makes more sense.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.