Module godot.docs.memorymanagement

Godot classes can be instanced with the engine's memnew template function. Other allocation methods such as D's GC new will not work with Godot classes, since the C++ engine is often responsible for deleting the objects.

After being created with memnew, most Godot objects are managed automatically:

Examples

class Test : GodotScript!Node
{
	@Method _ready()
	{
		Node a = memnew!Node;
		Node b = memnew!Node;
		a.addChild(b);
		memdelete(a); // MUST manually delete nodes that aren't in the tree
		// deleting the parent `a` also first deletes `b`

		Node c = memnew!Node;
		owner.addChild(c); // add `c` to the tree as a child of `this`
		// the tree will delete `c` right before it deletes `this` when the game is exited

		Node d = memnew!Node;
		owner.addChild(d);
		d.queueFree(); // remove and delete `d` once notifications and signals are finished being sent to it

		Ref!ArrayMesh mesh = memnew!ArrayMesh;
		// Ref will delete `mesh` at end of scope

		Ref!Texture tex = ResourceLoader.load("res://icon.png").as!Texture;
		// Ref will delete `tex` only if it isn't already loaded elsewhere.

		GodotObject manuallyManaged = memnew!GodotObject;
		memdelete(manuallyManaged); // MUST manually delete plain GodotObjects
	}
}