+2 votes

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

in Engine by (262 points)

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)

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?

1 Answer

+1 vote

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())
by (5,217 points)

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.

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().

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.