What is the correct way to instantiate a scene and then add the root node's children, rather than the root node itself, to another node? Using `reparent` causes errors

Godot Version

v4.3.stable.mono.official [77dcf97d8]

Question

I have some code that looks like this, for a Control node that I want to populate with children loaded from a saved scene. To maintain the correct layout it is important that the children of the scene root node are added as children, rather than the root node itself being added as a child.

@tool
class_name MyControl extends Container

const _init_scene_preload := preload("./MyScene.tscn")

func _init() -> void: # Same errors if placed instead in _ready
    self._init_scene()

func _init_scene() -> void:
    var scene_root_node := _init_scene_preload.instantiate()
    for child: Node in scene_root_node.get_children():
        child.reparent(self)

Using this approach, my console is full of warnings (first line) and errors (second line) like this in the editor:

scene/main/node.cpp:1579 - Adding 'NameLabel' as child to '' will make owner 'MySceneRootNode' inconsistent. Consider unsetting the owner beforehand.
scene/main/node.cpp:2518 - Condition "!is_ancestor_of(p_node)" is true. Returning: false

I have also received the same or similar errors when using different combinations of remove_child, set_owner, and add_child.

These warnings and errors do not seem to affect the functionality of the custom Control, but the spam in the console is inconvenient and makes me wonder if there is a problem with the behavior that I just haven’t noticed yet.

How can I handle this without the console being spammed with warnings and errors?

I think the problem is that the scene_root_node is not part of the scene_tree. You have to add it to the scene_tree first with add_child. Then you can reparent the children. Have you tried to just call self.add_child(child)?

1 Like

Adding the scene root node as a child first, and then using reparent, seems to resolve the error (second line), but it does not resolve the warning (first line) as mentioned above. I still get quite a lot of warnings when loading a scene with a node that does this.

Maybe child.set_owner(null) before child.reparent(self)?
This is what the message seems to recommend.

The docs recommend not to use reparent at runtime.
Unfortunately I can’t post a link, as the docs search function currently is broken.