Search code examples
javascriptthree.jshtml5-canvas

Three.js material.color.setHex on a MeshFaceMaterial


I have my code setup to change the colors of certain objects depending on different conditions. It currently uses loops such as

for (j = 0; j < objects[i].children.length; j++) {
    objects[i].children[j].material.color.setHex(0x1A75FF);
}

to set the color when needed from the render() function.

The problem though, is that some of the objects are MeshLambertMaterial and some are MeshFaceMaterial. The code above works perfectly for the MeshLambertMaterial, but it returns the error Cannot read property 'setHex' of undefined when it tries to run it on an object with a MeshFaceMaterial.

I have not been able to find a way to do this correctly, but if there is a fix that would also require making all of the objects in the scene to be MeshFaceMaterial in order to be able to set the color of any object with just one function, I would not mind doing so.

(What I don't want to do is to have an if statement that checks if the object has LambertMaterial or FaceMaterial and run a different set of code for each object in the loop!)


Solution

  • var materials = objects[i].children[j].material.materials;
    if ( materials ) {
        for ( var k=0,l=materials.length; k < l; k++ ) {
            materials[k].color.setHex( 0x1A75FF );
        }
    } else {
        objects[i].children[j].material.color.setHex( 0x1A75FF );
    }