How to change the parent of current node.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By usurun

I am trying to change the parent of my current node.

get_parent().remove_child(self)
get_parent().get_parent().add_child(self)
:bust_in_silhouette: Reply From: sparkart

When you unparent a node, the return value of get_parent() will be null. So you cannot use get_parent() when it has no parent.

var new_parent = get_node("/root/AnotherParent")
get_parent().remove_child(self)
new_parent.add_child(self)

Reference the parent before you unparent:
var new_parent = get_parent().get_parent()
get_parent().remove_child(self)
new_parent.add_child(self)

somehow I get ‘add_child’ in base ‘null instance’ after remove_child

func _process(delta):
	if target and get_parent() != get_node(target):
		var new_parent = get_node(target)
		get_parent().remove_child(self)
		new_parent.add_child(self)

DrSensor | 2020-07-05 15:55