How do I call the child of an instance and connect the script via code?

Godot Version



I have a VBoxContainer were I spawn so called “Feld” in. The “Feld” are a TextureButton with a Label Node as a child. If you click on the Feld you open a so called “formular” (a TextureRect with a RichTextLabel and a few TextureButtons).

I’m in the script of the VBoxContainer and I spawn as much Feld as needed via a simple “for i in variable”, but I struggle with two things.
Firstly: How do I access the text of the Label node that is a child of the instanciated Feld? I tried .get_child() or .text directly nothing seems to work.
Secondly: How do I communicate with the script of Feld? Usually I use signals with the node menu next to the inspector, but this is too specific for my porpuse. I need to make multiple connections with multiple instances only by running the same “for i in variable” command.

Thanks for Help.

Show some of your script! when and how do you need to access the labels is important, since they are instantiated the options are a little limited. get_child works if you know the index, for child in get_children() is great for iterating through all labels.

To connect to signals at run-time you’ll use the .connect function. for example

func _ready() -> void;
    var new_timer :=

func _on_runtime_timer_timeout() -> void:
    print("Hello from timer!")

Acessing child variables works like so, if they only have one child that is a label.

var feld := feld_prefab.instantiate()

var feld_label := clone.get_child(0) as Label # type casting with as
feld_label.text = "hello"

You can use the instantiated node as if it were the script.

const FELD = preload("res://feld.tscn")

func _ready():
	var spawned_feld = FELD.instantiate()

	print("Value: ", spawned_feld.find_child("Label").text)

You can use the find_child method to search for its children. Or you can save the reference inside your feld script to save on performance, and access it directly from there.

## On feld script
@onready var label_reference = $Label

And then use
spawned_feld.label_reference .text

1 Like