Losing mesh references when added to scene

Hello!
I am making an application that allows you to load gltf models locally and move/hide the models meshes. I have an array called models that holds all the models added to the scene, their name, file type and the actual scene produced by the GLTF loader. (Below is an example of an element in the models array)

I want to pass the children of each model into the scene. However, when I do this the models data looses all its meshes. Each element in models is passed into addToScene which adds the models to the scene but the object looses all its meshes. Any help on this would be great!

export function addToScene(object) {

  console.log("Before added to scene: ", object)
  let meshes = [];

  object.scene.traverse((object) => {
    if (object.isMesh) meshes.push(object);
  });

  meshes.forEach((mesh) => {
    scene.add(mesh);
  });
  console.log("after added to scene: ", object) //Meshes no longer inside object
}

Instead of this:


  meshes.forEach((mesh) => {
    scene.add(mesh);
  });

try:

  meshes.forEach((mesh) => {
    scene.attach(mesh);
  });

one scene object can only ever be in one place

const foo = new TREE.Mesh(...)
// Adding it to scene A
sceneA.add(foo)
// Three will now remove it from scene A
// And add it to scene B
sceneB.add(foo)

you must clone. i don’t think that attach is the solution, all it does is keep the previous world transform, but it’s going to be removed from the old parent nonetheless.

you can also pair three with react which gives you a sane workflow for gltf GitHub - pmndrs/gltfjsx: 🎮 Turns GLTFs into JSX components everything is re-usable by default and all assets are shared automatically. here’s a simple example of that https://codesandbox.io/p/sandbox/re-using-gltfs-dix1y

You don’t have to clone? OP is just moving the meshes out of a glb into the scene?..

I think because OP is using .add instead of .attach, the meshes are warping somewhere since they aren’t preserving their worldspace transform.

Thanks for the replies! I ended up taking all the glb models adding them to the scene and the holding a reference to the scene object in a react state variable!