Trying to set a new color in specific group of index's

I trying to set a new color in specific group of index’s. I successful set in a separate project (only js) using this code:

let color = new THREE.Color(0x62FF15);
for(let idx = 0; idx < nose.length; idx++) { 
     mesh.geometry.getAttribute("color").setXYZ( nose[idx], color.r, color.g, color.b ) 
 }

Result:
image

But, I trying this same code in a angular project this way:

funcName(indexes: number[]) {
    if (this.children.length > 0) {
      const color = new THREE.Color(0x62ff15);
      const mesh = this.children[0] as THREE.Mesh;
      for (let idx = 0; idx < indexes.length; idx++) {
        const colorAttr = mesh.geometry.getAttribute(
          'color'
        ) as THREE.BufferAttribute;
        colorAttr.setXYZ(indexes[idx], color.r, color.g, color.b);
      }
    }
  }

But, I receive this error:

ERROR TypeError: colorAttr is undefined

I really don’t understand why this not working.

The color attribute may not be initialized correctly. You can console.log your mesh geometry’s attributes and check if it’s there.

console.log(mesh.geometry.attributes)
1 Like

indeed, the color attribute is not initialized.

I noticed that in fact, as soon as I initialize the mesh, it no longer has the color property

code:

function (gltf) {
        gltf.scene.traverse(function (node) {
          if (node.isMesh) {
            mesh = node;
            const newTexture = textureLoader.load(
              URL.createObjectURL(new Blob([textureBlob]))
            );

            newTexture.flipY = false;
            newTexture.colorSpace = THREE.SRGBColorSpace;

            mesh.material.map = newTexture;

            mesh.material.morphTarget = true;

            scene.add(mesh);
            console.log(mesh.geometry.attributes)
}}

result:

Generally speaking, most GLTF models don’t come with a color attribute. You can initiate it this way:

const position = mesh.geometry.getAttribute("position");
const colorArray = [...position.array].map(() => 1);
const color = new THREE.BufferAttribute(new Float32Array(colorArray), 3);
mesh.geometry.setAttribute("color", color);

Then update it as you please.

1 Like

Your solution really solved the problem. I thank you so much for helping me.

1 Like