Issue with quickly spawning and destroying models

Recently I have discovered a memory leak in my game, and I have narrowed it down to a single script. This script constantly spawns cars on a road, tween the cars to the other side, and then destroy them. I have experienced memory of over 5000 MB. Any ideas on how I can improve the performance of this?

Any help would be appreciated. :slightly_smiling_face:

You could try using Debris instead of destroying them

local Debris = game:GetService("Debris")

Debris:AddItem(Instance, Time) --Time = how long it takes for the object to be deleted, set to 0 to delete instantly
1 Like

How is this different from destroying them?

Sometimes :Destroy() is wonky and doesn’t work properly

1 Like

Can you share the code where you suspect the memory leak is? We can’t give you any answers without code.

Insert references to those cars inside a table, then periodically traverse over the cars within the table calling the Destroy() function for each. This way if for whatever reason a car isn’t successfully destroyed from a first attempt to destroy it, repeat attempts will increase the chances.

1 Like

Are you destroying the Tweens that you create for moving them across the road as well as the cars? I’m assuming you’re connecting a Tween.Completed event to a function that destroyed the cars and depending on how your code is laid out the tweens may never be GC’d as a result.

1 Like

I can’t believe this never crossed my mind. Thank you this fixed the problem.

1 Like