What is the best way to deep duplicate a object and whole hierarchy of object?

Is there any built in method that can give me copy of whole model including its children and also materials. and both objects shouldn’t share any reference to each other.

function cloneNodeHierarchy(node: Node | Mesh, newParent: Nullable<Node | Mesh> = null, name: Nullable<string>) {
    let clonedNode: Nullable<Node | Mesh>;

    if (node instanceof Mesh) {
        // Clone the mesh
        clonedNode = node.clone(name ? name : node.name + "_copy", newParent, true);
        cloneMaterial(clonedNode as Mesh);
    } else {
        // Clone other types of nodes
        clonedNode = node.clone(name ? name : node.name + "_copy", newParent, true);
    }

    // Clone all child nodes
    node.getChildren().forEach((child) => {
        cloneNodeHierarchy(child, clonedNode, null);
    });

    return clonedNode;
}

currently I am using this custom function and it works fine for small models, it gets worse for bigger model.

Check instantiateHierarchy - Mesh | Babylon.js Documentation

Or, if you use Asset containers - instantiateModelsToScene - AssetContainer | Babylon.js Documentation

5 Likes

instantiateHierarchy seems to do the same thing that I am doing, so I am guessing that is the only way of doing and I am not doing something wrong here or it can’t be done in better way that this, right?

Here is the source for instantiateHierarchy