How to change the color of a gltf object?

I have a 3D model of a car. I would like to add a function to change the color of the vehicle upon clicking on one of the color choices. Here(Top Class Bottom Class) you can find the class structure of the 3D model. I’m aware that I need to apply a material upon the car body but I don’t know how exactly because this is a gltf model and not a standard three.js geometry shape.
Here’s the code I find the most relevant, if something is missing please tell.

function main() {
    // Color Palette
    const palette = document.getElementById('js-palette-slide');

    // Model Path
    let theModel = './cars/scene.gltf'

    // 3D Model Loader
    const gltfLoader = new THREE.GLTFLoader();
    gltfLoader.load(theModel, (gltf) => {
        const root = gltf.scene;
        scene.add(root);
    });

    // Colors To Choose From
    const colors = [
        {
            color: "000000",
        },
        {
            color: "545252",
        },
    ];

    // Add Colors To Palette
    function buildColors(colors) {
        for (let [i, color] of colors.entries()) {
            let colorpalette = document.createElement('div');
            colorpalette.classList.add('pallete__colors');

            colorpalette.style.background = '#' + color.color;

            colorpalette.setAttribute('data-key', i);
            palette.append(colorpalette)

        }
    }

    buildColors(colors)

main()
function selectSwatch(e) {
  let color = colors[parseInt(e.target.dataset.key)];
  let new_mtl;
  let new_color = parseInt('0x' + color.color)

  if (color.texture) {

    let txt = new THREE.TextureLoader().load(color.texture);

    txt.repeat.set(color.size[0], color.size[1], color.size[2]);
    txt.wrapS = THREE.RepeatWrapping;
    txt.wrapT = THREE.RepeatWrapping;

    new_mtl = new THREE.MeshPhongMaterial({
      map: txt,
      shininess: color.shininess ? color.shininess : 10 });

  } else

  {    
    new_mtl = new THREE.MeshPhongMaterial({
      color: parseInt('0x' + color.color),
      shininess: color.shininess ? color.shininess : 10 });
  }

  setMaterial(theModel, activeOption, new_mtl, new_color);
}

function setMaterial(parent, type, mtl, new_color) {
  parent.traverse(o => {
    if (o.isMesh && o.nameID != null) {
      if (o.nameID == type) {
        //o.material = mtl;
        o.material.color.set(new_color);                       
      }
    }
  });
}
1 Like

That not right. You can use the MeshBasicMaterial that comes with the model. All you need to do is to change the color.

o.material.color.set(new_color);

Every time I click on one of my colors I get an error message “parent.traverse is not a function” in my console.
It’s pointing me to

setMaterial(theModel, activeOption, new_mtl, new_color);
and
parent.traverse(o => {...