What's the best way to reference a child-node of a node I just instantiated?

Godot Version

4.3

Question

What’s the best way of addressing a value or a function of a child-node of a node I just instantiated?

My node:

EnvelopeOfMoney
|- ValueLabel (a Label node)
|- TickComponent (tscn)

TickComponent
|- Sprite2D (a Sprite2D node)
|- script "func tick(on_off):"

My code:

@onready var envelopeOfMoney = load("res://game/money/envelopeOfMoney.tscn")

func create_envelope(new_value, new_name, new_pos):
	var newSprite = envelopeOfMoney.instantiate()
	newSprite.set_name("envelopeOfMoney_" + new_name)
	$/root/Game/PlayerScreen/PlayerClickables.add_child(newSprite)
	newSprite.position = new_pos
	newSprite.find_child("ValueLabel").text = "€" + str(new_value)	# works
	newSprite.get_node("TickComponent").tick("on")					# works

Are find_child() and get_node() equivalent in this case, as I’m calling them on the node I just created? Or is one better?

Or is there a completely different way of referencing child-nodes that I’m missing?

Thanks,
Toby

Generally find_child is slower, you only want to use is when you don’t know the exact path to the node you’re looking for, and you just want to find it based on it’s name. So get_node is usually preferable, but they both work.

If you need a reference to them at other places in your code too, then it might be simpler to store them in a variable in the script attached to EnvelopeOfMoney, and just access them like newSprite.value_label.text = "..."

2 Likes

Brilliant, thanks!
Storing paths in the script attached to EnvelopeOfMoney was the technique I was missing!

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