I am working on a small scale game engine and have reached a point where I would like to destroy a Game Object (destroy meaning all references to an object become null). This is important because even if I remove the object from the list of objects I want to update, there could be lingering references still in memory from anything that had a reference to the object, preventing it from being collected. However after some research it is clear that there is no way to outright delete an object in C#. Despite this fact the Unity Game Engine has a method that can destroy an object outright.
I found this thread on the Unity forums that explains how Unity does it. It uses a method dubbed as a "smart reference" or a "handle" where there is a wrapper class of sorts around the actual object where only the wrapper references the real object everything references the wrapper. When the object needs to be destroyed, the wrapper removes its reference to the real object, allowing it to be freed when the garbage collector is ready.
This all makes sense to me I am confused about some details. For one, how could I get properties and call functions of the real object class directly from the wrapper? Unity allows you to access properties directly like so gameObject.transform
instead of gameObject.obj.transform
implying one of four things
- The GameObject wrapper is filled with methods and properties that just call the real object's methods and properties (seems horrible to maintain having to make sure every method has a duplicate)
- The GameObject wrapper stores the actual data and returns null on every property if the real object was destroyed (this does solve other things messing around with objects that no longer exist but it keeps all of the data in memory so does not solve anything)
- Something related to C++ which I wouldn't be able to implement in pure C#
- Some method I don't know about
If anybody has the answers I need or knows a source I could learn more about these "smart references" please let me know, it would be greatly appreciated