Add_child in _ready won't display in scene tree, visibility toggle also behaves wrong

Godot Version

4.2.1

Question

I attempted to add some child nodes in _ready function of parent node.

void WindarineNode::_ready() {
    _body = memnew(MeshInstance3D);
    _body->set_name("Body");
    if (!_bodyMesh.is_null()) {
        _body->set_mesh(_bodyMesh);
    }
    if (!_material.is_null()) {
        _body->set_material_override(_material);
    }
    add_child(_body);
    _wireframe = memnew(MeshInstance3D);
    _wireframe->set_name("WireFrame");
    if (!_wireframeMesh.is_null()) {
        _wireframe->set_mesh(_wireframeMesh);
    }
    _wireframe->hide();
    add_child(_wireframe);
    _collision = memnew(CollisionShape3D);
    _collision->set_name("Collision");
    if (!_shape.is_null()) {
        _collision->set_shape(_shape);
    }
    add_child(_collision);
}

But children nodes didn’t occur in the SceneTree but they behaves correct in the scene viewport. This is the first problem.
And when I toggle the eye button in the scene tree of my parent node. It behaves right when I hide the node(I mean the children nodes hiding), but children nodes won’t show when I toggle the eye button again. This is the second problem.
image

Environment: Editor, not runtime.

You need to set the Node.owner property of the children to point to the root node of the scene.

Any method to get the root? get_tree()->get_root() returns a Window object, how can I get the root node?

It’s the root of the current scene you are editing not the root of the SceneTree.

You can try setting owner to the same value the parent of the node you added has:

    _body = memnew(MeshInstance3D);
    _body->set_name("Body");
    if (!_bodyMesh.is_null()) {
        _body->set_mesh(_bodyMesh);
    }
    if (!_material.is_null()) {
        _body->set_material_override(_material);
    }
    add_child(_body);
    
    _body.set_owner(get_owner());

Thanks. It only works when the node is already in the tree, but doesn’t work when I attempt to add a new node, I print the owner of the parent node and it returns nullptr. Seems _ready is called before setting the owner. Maybe I can do these initialization in the first frame of _process.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.