How Can I Disconnect a Touched Function Whenever I Clear the Workspace?

Hello all,

Lately I have been trying to fix some memory leaks in my game, and I found that my game’s untracked memory substantially increases every time I clear/add a map - say for a round-based game.(These are big maps by the way with many scripts) I have a lot of .Touched scripts, and I want to disconnect these events once the map clears. How can I go about doing this? This is my hacky way of going about it.

local connection = part.Touched:Connect(function(hit)
        -- do stuff
end)

while true do
        if mapclearing == true then
                connection:Disconnect()
                break
        end
        wait(1)
end

Note that this method does work, but you can already see a problem with this if I’m going to use it for over 100 .Touched scripts per map.

1 Like

When you clear the map, do you :Destroy() it? If you do, then nothing else needs to be done since Destroy disconnects all connections automatically.

2 Likes

Yes, I do a for loop through the entire workspace and destroy every thing except the lobby. However, this action causes untracked memory in my game to increase by about 50-100 MB. Any ideas on what might be causing this?

And also good to know that I don’t have to disconnect .Touched events thanks a bunch

2 Likes

I don’t know. If you look up “untracked memory” in the forum you’ll find that everyone has a problem with it growing out of their control for no reason.

What I can tell you is that signals (connections to events, basically) are actually tracked in their own category. If you want any proof that Destroying does in fact disconnect connections, here’s the memory consumed by a baseplate with 10000 connections to the touched event:

image

Here it is after the baseplate is destroyed:

image

6 Likes

Does debris do the same thing? I’m spawning projectiles with touched events connected to them and am wondering if adding it to debris will disconnect it properly?

1 Like

Adding objects do debris essentially schedules Instsnce:destroy() to be called upon them at some point. So, I believe it should disconnect events, yes.

3 Likes