Closed
Description
I've seen a lot of new users of the C++ bindings get stuck on unhelpful/non-obvious errors caused by using Godot classes like normal C++ classes. There are certain "rules" for how they should be used that aren't clearly mentioned in the readme or official docs. The examples follow them, of course, but it's not obvious from there that the "normal" C++ ways don't work.
I would suggest adding this section to the bottom of the readme:
Using Godot classes
- Create instances that inherit Object (including your own registered classes) using
_new()
, not C++'snew
operator.
Sprite *sprite = Sprite::_new();
- Destroy nodes using
queue_free()
, not C++'sdelete
operator.
some_old_node->queue_free();
- Wrap instances that inherit Reference in
Ref
instead of passing around raw pointers. They are ref-counted and do not need to be freed manually.
Ref<Texture> texture = resource_loader->load("res://icon.png");
- Pass the core types that do not inherit Object by value. The containers (Array, Dictionary, PoolArrays) manage their own memory and do not need to be explicitly initialized.
Array ints;
ints.append(123);
return ints;
- Initialize your classes in their
_init()
method, not their constructor. The constructor does not yet have access to the base class's methods. - Cast objects using
Object::cast_to
, not unsafe C-style casts orstatic_cast
.
MeshInstance *m = Object::cast_to<MeshInstance>(get_node("ChildNode"));
// m will be null if it's not a MeshInstance
if (m) { ... }
Let me know if there are more non-obvious rules missing from the list, or if I can improve/condense any of the phrasing.
Metadata
Metadata
Assignees
Labels
No labels