0 votes

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!

Godot version 3.3.2
in Engine by (35 points)

Thanks to both of you, it works perfectly now! ;)

2 Answers

0 votes
Best answer

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.

by (3,379 points)
selected by
+1 vote

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/

by (69 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.