Do I have to disconnect touch event even when part is destroyed?

local object = pathobject -- object as in random part in workspace or whatever
if object then 
    object.Touched:Connect()
     -- random logic
     object:Destroy()
    end)
end

Or

local obj = "objectunamehere"
if obj then 
local E -- I dont know what you call this but maybe 'event handler'??
E = object.Touched:Connect(function()
object:Destroy() E:Disconnect()
end)
end

dont they do the same? because the first code shows part destroyed meaning that the function is no longer active but same does the second one? which is best for performance? I just saw this from a free model rocket kit and thought I’d like to ask whats the main difference Thanks

5 Likes

When a part gets destroyed, all event connections to that part are also disconnected automatically so you don’t have to worry about that.

20 Likes

It doesnt work for me, Touched event fires even after my part is destroyed

1 Like

@builderIV How would your touched event get triggered if the part doesn’t exist anymore? :thinking:

What may be happening is that you have code logic that takes enough time to run, that the part is removed before the code is finished. Example -

part.Touched:connect(function()
    print("started waiting at"..tick())
    wait(10)
    print("finished waiting at "..tick())
end)
wait(20)
part:Remove()
print("Removing part at "..tick())

Now it shouldn’t be possible for you to see a tick(), timestamp, that says “Started waiting at”, that is timed before “Removing part at”, but you could possibly see a “finished waiting at” time that comes after the Remove, because the function was already triggered before the part was removed.

Sorry I know you posted this a while ago, hopefully this helps if you didn’t already solve your issue somewhere else :+1: