Adding Child with Rust GDExt

Godot Version

4.3

Question

I am trying to dynamically add children to a node during _ready. I load the scene to add, instantiate it, and add the child, but it is not listed afterward when I list the children, nor is it found later on in the program’s run when I specifically look for the child.

Rust Code Snippet:

let scene = load::<PackedScene>("res://source/match/units/traits/Selection.tscn");
let mut node = scene.instantiate().unwrap();

let unit_var = self.base_mut().get(StringName::from("radius"));
node.set(StringName::from("radius"), unit_var);

godot_print!("Add: {}", node.get_name());

self.base_mut().add_child(node);

for child in self
    .base()
    .find_children_ex(GString::from("*"))
    .recursive(false)
    .done()
    .iter_shared()
{
    godot_print!("Child: {}", child.get_name().to_string());
}

Output:

Add: Selection
Child: Geometry
Child: CollisionShape3D
Child: Movement
Child: Sparkling

Update: The Selection Node3D I created does show up in the remote scene tree in the proper place, however it does not appear in the child search commands.

Solution: For others using Rust, you have to set the owner after adding the child, otherwise it will not be listed in the child search functions. So the fixed code is:

self.base_mut().add_child(node.clone());
node.set_owner(self.base().clone().upcast::<Node>());

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