Search code examples
godotgdscriptgodot4

Why is the duplicate of a node's random child null? is there any way to fix or work around it?


So I took a random node from a parent and duplicated that node. For some reason, the Node3D is a null instance, so I can't really do anything with it. This is my code:

func _ready():
   MoveNode
func RandNode(P):
    P.get_child(randi() % P.get_child_count()).duplicate()

But, when I try to move it:

func MoveNode()
    var NewNode = RandNode($ParentNodePath)
    NewNode.global_translate = $OtherNodePath.global_translate

It gives me an error saying that NewNode is null.


Solution

  • You duplicated the node, but forgot to return it:

    func RandNode(P):
        return P.get_child(randi() % P.get_child_count()).duplicate()
        ^^^^^^