godotengine / godot

Godot Engine – Multi-platform 2D and 3D game engine
https://godotengine.org
MIT License
91.09k stars 21.18k forks source link

"add_child(node)" doesn't work inside "_ready()" function #233

Closed amigamagic closed 8 years ago

amigamagic commented 10 years ago

Let's suppose I want to dinamically create a node 'newNode' from within a script, when some node N enters the scene... So, I should add the relevant code inside the "_ready()" function of the node N script. Something like:

from inside the script attached to the node N:

_ready():
   ...
   var newNode = preload("res://subScene.scn").instance()
   get_node("/root").get_child(0).add_child(newNode)
   ...

But this will not work: newNode will not be added to the scene. Instead, it will work if you call the add_child(node) from within another function of the script attached to the node N.

For now, a workaround is to use a "call_deferred" inside the _ready() function, so that the above code should be like that:

_ready():
   ...
   var newNode = preload("res://subScene.scn").instance()
   get_node("/root").get_child(0).call_deferred("add_child", newNode)
   ...
someoneaaron commented 10 years ago

I guess it should be written like this: get_node("/root").get_child(0).add_child(newNode) not ("newNode")

amigamagic commented 10 years ago

Typing error. Thanks for reporting it. I corrected the above code. Of course, the bug remains.

akien-mga commented 9 years ago

Is this still valid in the current master branch?

vnen commented 8 years ago

Can't reproduce this in current master. Tested with the same code and the child node was added correctly even inside _ready().

ballerburg9005 commented 5 years ago

I experience very much the same issue in 3.1.1.stable.official / Linux 64bit.

func _ready():
    var newbox = duplicate(8)
    newbox.translate(Vector3(0,0,-1))
    get_parent().call_deferred("add_child", newbox)  # working as expected
#      get_parent().add_child(newbox)                    # not working at all
#      add_child(newbox)                                 # this would be working, but I don't need that
pass 
eon-s commented 5 years ago

@ballerburg9005 that is not a bug, in the debugger on the errors tab you will find something like Parent node is busy setting up children, add_node() failed. Consider using call_deferred("add_child", child) instead.

aabmets commented 5 years ago

I was about to report this as an issue when I stumbled upon this thread. This should be documented. I can't describe how much time I have wasted trying to find a solution as to why TF I can't add a child to the root node.