I’m getting into optimization with my code, and so far I’ve optimized all of my old scripts along with enabling StreamingEnabled and now my game is buttery smooth despite its sheer size.
For coding, when should I disconnect connections? And I’m looking for more than the vague answer “Oh, when you don’t need them anymore”
Like, for example, do I have to disconnect/destroy connections with scripts in StarterPlayer/StarterCharacterScripts on humanoid death or do they automatically destroy on death? I feel like I’m overthinking this, but I just want to make sure I know what I’m doing when I’m coding
But that is precisely when you do. Connections don’t inherently de-optimize your game.
If from PlayerScripts, you might still be referencing an old character.
Since for some reason Roblox doesn’t
:Destroy() the character when respawned I just tack this inside my
player.CharacterRemoving:Connect(game.Destroy) -- force destroying of the character
:Destroy also calls itself recursively on the descendants of what the method was called on and implicitly disconnects any event connections.
Disconnect is essentially for when you do not need to listen to a certain event. Please do note that when an instance that has a connection doesn’t exist anymore (Destroyed, Respawned like a Character), it will remove the connection automatically.
Sometimes you don’t need to disconnect an event at all.
Let’s say you added a Touched event to a BasePart. You do not need to disconnect it when a part touches as you can create a debounce system.
But as @sjr04, Roblox doesn’t really Destroy the character when you respawned.