Can´t duplicate child node

Godot Version

4.2

Question

Having the following node structure (example):


- node1
- node2
    - node3
      - node4

Need to duplicate node4 and reassign the copy to another parent (node1). I’m using duplicate() and reparent() but instead of duplicating, it’s removing from node3 and adding to node1 children

I’m not sure how are u doing it. Would be good to have your code here to try to figure it out.

I tried with the following and worked as expected:

var node_to_clone := get_child(1).get_child(0).get_child(0) # node4
var clone := node.duplicate()
get_child(1).add_child(clone) # add the clone as a child of node1

You can find here the duplicate method documentation and see that it returns a new node that u can handle, but it’s not in your scene tree yet, so u can’t reparent it.

1 Like

Heres my code:

		var copy = node3.get_child(0)
		copy.duplicate()
		copy.reparent(self)

I’m running the script in node1. Using add_child give me error: “Can’t add child … node already has a parent 'items”

Hmmm try with this:

var node4 = node3.get_child(0)
var copy = node4.duplicate()
add_child(copy)

It worked for me

1 Like

This should work for you.
You can’t reparent a node that is not in the scene tree.

Since your script is in the node1, you can do as @Kaboom57 replied using only add_child(your_clone_here), since it’s already the owner of it.

Just find the child, clone it and call the add_child method passing it as a parameter in any node u want to be it’s parent.

Yeah it woked. Thanks

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.