Traversing the Loaded Model

After you've loaded your model, here's how you work with what's in it

Traversing the Loaded Model

A loaded model is a tree of objects: groups containing groups containing meshes. To access individual parts, you traverse the tree. Three.js provides the traverse method on every Object3D, which visits every descendant recursively.

typescript
loader.load('/models/robot.glb', (gltf) => {
  const model = gltf.scene;

  // Visit every object in the model
  model.traverse((child) => {
    if (child.isMesh) {
      // Enable shadows on all meshes
      child.castShadow = true;
      child.receiveShadow = true;

      // Log the mesh name (set in the 3D tool)
      console.log('Mesh:', child.name);
    }
  });

  scene.add(model);
});

Object names come from the 3D tool. If a your or your 3d artist named a mesh "Wheel_FL", that's what child.name will be. This is how you find specific parts of a model to manipulate independently:

typescript
// Find a specific part by name
const wheel = model.getObjectByName('Wheel_FL');
if (wheel) {
  wheel.rotation.y = Math.PI / 4;  // turn the wheel
}

// Find all meshes and store them
const meshes = [];
model.traverse((child) => {
  if (child.isMesh) meshes.push(child);
});
←   Common loading errorsRaycasting and Mouse Events   →