How to unparent nodes

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

I’m trying to unparent nodes during runtime. I don’t think godot supports this or am I mistaken?

I’m not sure, what you try to achieve but if a node is part of the scene tree it has to have a parent, the only way to unparent it is to remove it from the scene tree

To do that, you can use Node.add_child() and Node.remove_child()

For example

func _ready():
    var my_node = load("res://my_node.tscn").instance()
    # or Node2D.new() or whatever it is you need :)

func parent():
    add_child(my_node)

func unparent():
    remove_child(my_node)

atze | 2017-03-17 22:52

I have two nodes and one of those nodes has a child. What I want to do is move the child to the other node but if I use remove_child the child node disappears. Is there a way to transfer ownership of a child node to another node?

vonflyhighace2 | 2017-03-18 00:02

:bust_in_silhouette: Reply From: avencherus

Should be able to do something like this. Objects will exist after remove_child, it isn’t until they’re freed, that they are gone.

func _ready():	
	var child = get_node("a/node")
	get_node("a").remove_child(child)
	get_node("b").add_child(child)
	
	for child in get_node("b").get_children():
		printt(child, child.get_name())

Keep in mind that, with this method, _enter_tree and _ready (only godot 2.x) will be triggered again when you re-insert the node on the tree.

eons | 2017-03-18 10:35

Yes, something to look out for if there is script on those nodes… And more precisely, _exit_tree() as it’s removed, then _enter_tree() followed by _ready().

avencherus | 2017-03-18 15:50