Accessing/amended properties of dynamically created child object in scene

Godot Version

Godot 4.4.1

Question

Is it possible to access properties of child objects dynamically created in a scene?

Please can someone help with this issue as I’m not sure how to go about this.
I have a ‘child scene’ that has a CharacterBody2D (e..g. Rectangle/Box shape, with Sprite2D, CollisionShape2D, and a Label (Label’s text property set to “1” in Inspector). Effectively, we have a box shape with the number 1 displayed. Child scene saved..

Now, I want to create the child object dynamically in my Main scene, display it centrally AND THEN modify the value shown in the child object’s Label.text property. Is this possible?

Main scene code so far…

extends Node2D

@onready var child_scene = preload("res://scenes/child.tscn")

func _ready() -> void:
	if child_scene:
		display_child()			
		
func display_child():
	var new_child_scene = child_scene.instantiate()
	add_child (new_child_scene)
	new_child_scene.position = 
                 Vector2(get_window().size.x/2,get_window().size.y/2)

To get the label, you can use the get_node method on the root node.

var label := new_child_scene.get_node("Label")

Then you can set the label’s text just like any other property.

label.text = "Hello World!"

If you don’t need to store the label in a variable, you can do the same thing in one line.

new_child_scene.get_node("Label").text = "Hello World!"

Oh, thank you. I shall give it a try.

Thank you . that worked!..YAY!

1 Like