Tween Object Completed

What should you do after a tween object completed to prevent data leaks?

Apparently, you can’t use :Disconnect() on tween objects.

You disconnect the RBXScriptSignal returned by events, and not the tween object itself.

local completedEvent; completedEvent = tween.Completed:Connect(function(...)
    completedEvent:Disconnect()
end)

Note that completedEvent is defined before being set (local var; var = ... instead of local var = ...). This is necessary if you want to be able to access the variable inside the function passed to the event.

2 Likes

What happens if the object being tween was deleted before it finishes, would that be GC’d or will it cause a leak?

Couldn’t you just destroy the tween if you’re done with it? That should disconnect all the signals, and get cleaned up if you have no references to it, as far as I know.

Another thing why is there 2 CompletedEvent with a semi colon between them?

Yes.

Semicolon is optional, but helps distinguish that there are two separate statements there. For better visibility, it’s the same code as:

local completedEvent

completedEvent = tween.Completed:Connect(function(...)
    completedEvent:Disconnect()
end)

As for why there are two completedEvents, it’s because if you declare the variable as you’re setting it, you won’t be able to access it from within the function passed to the event. You don’t need to declare separately if you aren’t disconnecting from within the event.

4 Likes

So basically,

if you call a bunch of Tween Objects :Play() and dont disconnect it can potentially leak

Probably not. I imagine the tween object gets garbage collected at some point when it’s no longer playing and loses its last reference to a variable (i.e. scope that variable was in has terminated). Roblox is generally pretty good at handling things like this behind the scenes. I wouldn’t worry about prematurely optimizing event disconnections unless it actually becomes a problem.

That being said, disconnecting events can be useful for non-performance purposes such as enabling/disabling controls through UserInputService events.

2 Likes