+1 vote

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 (Abc.gd) :

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/Abc.gd").new()


var new_ab = Abc.Ab.new(x,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?

in Engine by (135 points)

2 Answers

+4 votes
Best answer

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 Abc.Ab.new(), 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/Abc.gd").new()

You added .new() here. So this will create an instance of Abc.gd, 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 Abc.gd. 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/Abc.gd")

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

And this will still work:

var new_ab = Abc.Ab.new(x,y)

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

by (29,036 points)
selected by
+1 vote

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

Like so:

Class Ab:
extends Node2D

Then you can call newab.queuefree() when you're done with it.

by (47 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.