When a script is destroyed, will the objects created and referenced by the script be destroyed?

Hello
I have an NPC model and a script inside.
In the script I create several objects, which are referenced only by local variables inside the script but are not parented to the NPC.
If I destroy the NPC, the script will be destroyed, but will these objects be garbage collected? (I am concerned about memory leaks).
I see that some people are using an artificial container called “maid”, but I am not sure if I need this…

Thanks in advance

1 Like

The objects are not linked to the script, so they will not be destroyed

1 Like

The objects are not under the script, but they are referenced only by variables inside the script.
I understand that they will not be destroyed immediately, but my question is whether they will be garbage collected or I need to destroy them manually

1 Like

As hbgnhu and mooonc0w said, the script isn’t the direct parent to the objects. Although, if you want to delete them you could probably put them in folders or a table and call :Destroy() from there… I’m not sure but it is an idea!

1 Like

Since there is no reference to them, they will most like be garbage collected…
But creating and deleting scripts to remove variables isn’t good practice. If you don’t need the variables, don’t bother.

1 Like

If the Instances are parented to nil and there are no longer references to it within the script it will be destroyed.

It seems there is some behind the scenes optimization done here.

Case example with creating Instances in a loop without :Destroy

Of course I recommend using :Destroy() in your code and using maid to ensure your objects are no long being used and such.

1 Like

The instances are not parented to nil. They have valid parent outside of the NPC. But they are referenced only inside the script, which is destroyed.

1 Like

Why not just call :Destroy() when the script is being destroyed?

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.