InstancedMesh,How to change the vertex color of an instance

Hello, I have created multiple instances using InstancedMesh, and I want to change the color of some vertices in one instance without affecting other instances, I tried the method, but it didn’t work

const geometry = new THREE.BufferGeometry();
    const vertices = []; // vertex array
    const colors = []; // color array

    for (let i = 0; i < 10000; i++) {
      const x = Math.random() * 2 - 1;
      const y = Math.random() * 2 - 1;
      const z = Math.random() * 2 - 1;
      vertices.push(x, y, z);
      colors.push(Math.random(), Math.random(), Math.random(), 1);
    }

    geometry.setAttribute(
      "position",
      new THREE.BufferAttribute(new Float32Array(vertices), 3)
    );
    geometry.setAttribute(
      "color",
      new THREE.BufferAttribute(new Float32Array(colors), 4)
    );



    const material = new THREE.MeshBasicMaterial({
      vertexColors: true,
      transparent: true,
    });

    const instanceCount = 3;
    const instancedMesh = new THREE.InstancedMesh(
      geometry,
      material,
      instanceCount
    );
    scene.add(instancedMesh);

 
    // test, change the color
    setTimeout(() => {
        // the second instance
        let instanceID = 1
        const attr = geometry.getAttribute("color")
        const count = attr.count
        // Change the color of the second vertex of the second instance
        attr.setXYZW(instanceID * count + 1, 1, 0, 0, 1)
        attr.needsUpdate = true // did not work, how to do?????
    }, 3000);

All instances share the same vertex attributes. You can set instance attributes, including one solid color per instance, which would be multiplied against the common vertex colors. If you need to override specific vertices only in specific instances, I think you’ll need custom shaders using vertex and instance IDs to achieve that.

Can you give me an example of that? Thank you

The webgl / instancing / scatter example uses instance colors, multiplied against the base colors of the mesh. See this code snippet from the example:

As far as custom shaders that target specific instance IDs and vertex IDs, I don’t have an example at hand.

2 Likes