Objects inheriting Reference
must not be freed explicitely. They get destroyed only once nothing else references them. If you have an array of references, simply setting the item to null
will free it, if it's the only place it is referenced.
You say you want to use free()
from inside the object itself, however I can only tell you this is a bad design. It can have really nasty consequences.
In order to use free()
, your script must inherit Object
(or a class based on Object
which doesn't inherit Reference
). But be careful about this, because it destroys the object right now. Any piece of code following the line with free()
may potentially crash the game, because the object will be gone.
The most common pattern where an object "kills itself" is in the case of nodes, using the queue_free()
function.
Indeed, objects inheriting Node
don't inherit Reference
. So they are not ref-counted, and freeing them immediately frees them. However, because doing this immediately can lead your code to step over itself and crash, queue_free()
is preferred so that the actual destruction happens during idle time, when scripts are done running.
If your object is also referenced inside an array somewhere, you may want to emit a signal so that the holder of the array removes the object from it. Or better, delegate destruction to this holder, so you won't need signaling.