How to Connect a signal after add a child node on same Script

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Riderick

Hi! I would like to know if it is possible to connect a signal after adding a child node from code in the same script (if possible). Since apparently after reviewing it, Godot tries to connect first but does not find the node because it does not exist. This is the code.

var ItemList1 = ItemList.new()
add_child(ItemList1)
get_node("ItemList1").connect("item_selected", self, "_on_ItemList_item_selected")

Error:

Attempt to call function 'connect' in base 'null instance' on a null instance.

Thank you very much!

Thanks to both of you, it works perfectly now! :wink:

Riderick | 2021-08-24 15:26

:bust_in_silhouette: Reply From: boruok

you’re trying to connect to node by variable name, when method get_node( NodePath path ) required nodepath which is string.

below is code when you don’t know your nodepath, you can connect to signal before instantiating any node.

var ItemList1 := ItemList.new()
ItemList1.connect("item_selected", self, "_on_ItemList_item_selected")
add_child(ItemList1)

here is article how to use nodepaths, highly reccomended, because is essential → https://kidscancode.org/godot_recipes/basics/getting_nodes/

KidsCanCode is overcomplex hogwash. ‘Kids’ can code? What kids are they talking about? The height of Baron Trump?

You’re a good person for helping people on here but websites like KidsCanCode are funded by major companies and government entities trying to widdle-down the competition in the software development market. Just like any other industry, the less people involved, the greater a monopoly for those at the top. No conspiracies here to assume that the establishment would want less competition through outright confusion of complex topics. For example, people have been brewing alcohol since hunter/gatherer times – yet when you Google how to brew alcohol – every page you see looks like rocket science for the reason I stated above.

Blockmaster27 | 2023-01-24 16:33

:bust_in_silhouette: Reply From: timothybrentwood

Simply changing:

get_node("ItemList1").connect("item_selected", self, "_on_ItemList_item_selected")

to:

ItemList1.connect("item_selected", self, "_on_ItemList_item_selected")

should work since the variable ItemList1 references the object you want to connect the signal from. The reason get_node() doesn’t work is because I believe add_child() updates at the end of the frame so get_node() wouldn’t be able to find the new child until the next frame.