add_child() doesn't work on any node other than the node I'm calling the function from. Why is it so?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Vinvirinvi
var scene = preload("res://Scenes/MyScene.tscn")
var node = scene.instance()

get_parent().add_child(node)
# Doesn't work. get_parent() returns a viable object, but the node won't get parented to it. When I check the parent of the node it returns null, and debugger gets overflown with errors of this type: C Error: Condition ' !is_inside_tree() ' is true. returned: get_transform()

add_child(node)
# But this works fine

I just can’t get what’s wrong with it. Maybe I’m not seeing something obvious? Is it a known bug? If so I couldn’t find a corresponding issue. Is this an intended behaviour? This is incredibly frustrating:(

I regularly call add_child() from nodes other than the node I’m adding the child to, and it works fine. Is the script you’re calling it from a singleton or something? What type of node is get_parent() returning?

Diet Estus | 2018-06-10 02:47

No, I don’t call it from a singleton. I tried to parent to nodes of different types. It doesn’t work with Node2D and Position2D - the ones that I actually need, because I need the parent node to have a position in space. It also doesn’t work with Viewport. Interestingly, it works with Node, but I can’t use Node in my case.

Vinvirinvi | 2018-06-10 11:30

:bust_in_silhouette: Reply From: daemeh

I got a different error, something about the node still setting up children.
Here’s what you can use in this case:

    		get_parent().call_deferred("add_child", c)