A player fires a remoteevent with an object and when the object gets destroyed on both the server and client the object does not turn nil on the server. Why does this happen?
reproplace.rbxl (16.4 KB)
Launch with 1 player and check the server output.
Did you print the object or the object’s parent?
Destroying results in setting the parent to nil.
I printed the object, not the object’s parent.
There you go. Destroying will result in setting the parent to nil. If the object is still referenced by a variable or something else, it may not disappear completely(causing memory leak?).
Should i make the object nil in the script if its destroyed aswell to prevent memory leak?
I guess you could set the variable to nil in order to remove the reference to it.
The gc cannot tell if you have done using the resource by just using :Destroy(). You are asking that :Destroy() should set all references to nil and its children.
This does have the benefits of being able to read the instance after it has been destroyed meaing that any other code using the instance will not fail on reading properties.
:Destroy() was added to lock the parent and its children to prevent it for being added back into the game.
Generally you should not be setting things to nil and instead rely on the variable being cleaned up after it goes out of scope. Setting variables to nil can cause convoluted code.
General point on memory
I often create a new scope when setting up modules as you end up using resource which are no longer needed.
local tool
do
-- new scope
local storage = game:GetService('ServerStorage')
local tmpTool = storage.Tool:Clone()
-- edit tool
tool = tmpTool
-- variables fall out of scope and are gc
end
What’s the purpose of the scope or how is it related to the OP? Tool is still a strong reference to an instance as the chunk in the do-end block sets the value of an upvalue, so scoping just becomes organisational in this circumstance.
Using scope is just a general point not related to the OP but with the concept of memory management and avoiding setting variables to nil.
I did the post in a rush its updated now
That’s context dependent, really. You’re still going to end up needing to set some variables to nil. A do-end block can cull most of it but if you really want to go on the buff with memory management, you can’t avoid setting variables to nil. Especially in your example.