how to free class object memory

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By sry295

in Node2D it has something like queue_free or remove_child
but my own create class in new .gd file can’t use them
file example ( :

extends Node    

class Ab:
    var a:int
    var b:int

    func _init(_a,_b):
        self.a = _a
        self.b = _b


then use it in main Node2D file with

extends Node2D

onready var Abc = load("res://script/").new()


var new_ab =,y)

is i use it wrong? is there any garbage collector?
i switch my variable to reference new object a lot
how do i free memory for old unuse class object?

:bust_in_silhouette: Reply From: SawmillTurtle

If you have your class inherit from Node2D, you can call queue_free().

Like so:

Class Ab:
extends Node2D

Then you can call new_ab.queue_free() when you’re done with it.

:bust_in_silhouette: Reply From: Zylann

Rule of thumb:

  • If an object inherits Reference, it will be automatically managed.
  • If an object does not, it needs to be freed manually, or freed by its parent.

Scripts and classes declared using the class keyword will inherit Reference if they have no extend specified.

So when you do, it will return an instance of Ab, which is a reference, so it will be automatically freed as soon as it gets out of scope. You should not use free() on them.


onready var Abc = load("res://script/").new()

You added .new() here. So this will create an instance of, and this one extends Node2D. Nodes don’t inherit Reference, so they are not automatically freed. If you don’t add them to the scene tree, you have to delete them using free() once you are done with them.
However, if you add them to the tree as child of another node, they will be freed automatically when their parent is freed. Alternatively, nodes can be freed using queue_free().

Note about your current case:
If all you wanted was to create an instance of Ab, you don’t need to create an instance of A script and an instance of that script are two different things.
All you need to do is this:

# Loads the script without creating an instance of it.
var Abc = load("res://script/")

# This also works if you don't have cyclic dependencies,
# with the advantage of providing better completion
const Abc = preload("res://script/")

And this will still work:

var new_ab =,y)

You also won’t need to free Abc because scripts are resources, and Resource inherits Reference.