I am working on A-Frame with a 3D model imported from Blender. Multiple meshes of this model have 2 or more materials assigned to them.
I can change the material properties of meshes that have only 1 material
However, when it comes to changing the material properties of meshes that have more than one material, I run into the following problem:
"Uncaught TypeError: Cannot set properties of undefined (setting 'opacity')"
The code I am using is the following:
<script>
AFRAME.registerComponent('modify-materials', {
init: function () {
// Wait for model to load.
this.el.addEventListener('model-loaded', () => {
// Grab the mesh / scene.
const obj = this.el.getObject3D('mesh');
// Go over the submeshes and modify materials we want.
obj.traverse(node => {
if (node.name.indexOf('muros') !== -1) {
node.material.opacity = 1;
}
});
});
}
});
</script>
I was assuming the solution was going to be as simple as treating the materials as an array, but it didn't work:
node.material[0].opacity = 1;
node.materials[0].opacity = 1;
I have also searched how to iterate between the id's of materials but I have not been successful.
Could someone help me understand how I can access the 2,3,4,n materials?
Each mesh node should have only one material. So you should probably search by the material name, and modify the ones that match:
obj.traverse(node => {
if (node.material.name === "material_one") {
node.material.opacity = 1;
} else {
node.material.opacity = 0.5;
}
});
I remember doing something similar - check it out here. Knowing the material name, you can modify its properties (like here):
<a-entity gltf-model="./model.gltf"
material-modifier__MaterialName="emissive: 0xffff00"
material-modifier__AnotherMaterialName="color: 0xff00ff"
></a-entity>