How to change the parent of a node from GDScript?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Zylann
:warning: Old Version Published before Godot 3 was released.

I’m trying to put a node under another parent from script, but surprisingly I got many errors.
First, I tried:
new_parent.add_child(node)
But the debugger says: “node already has a parent”.
Ok, so I try to remove the node from its parent first:

node.get_parent().remove_child(node) # error here  
new_parent.add_child(node)  

But again, error: This function can’t be used during the in/out signal.
I seem to get the behaviour I want, but something went wrong, and I want to know how to change the parent properly?

Do you happen to have some code we can look at?

The_Duskitty | 2016-03-20 23:43

I updated my post, the markdown was wrong on the second snippet.

Also, I just tested the second snippet on a blank project with simple Nodes, and it worked. But in my project it happens inside an Area2D.body_entered() callback. maybe it’s related?
I can’t extract the code easily right now, I need some time.

Also, any idea why the second error usually happens, and how to avoid it?

Zylann | 2016-03-21 00:42

:bust_in_silhouette: Reply From: henkz

It looks like areas are locked during area_enter/exit. I think it should work if you use it with call deferred. Something like:

  call_deferred("reparent",node)

func reparent(node):
  node.get_parent().remove_child(node) # error here  
  new_parent.add_child(node) 

Or maybe it’s better to just add the node to a var or array and do it in next _process.