Hi i’d like some help if i needed to use a function to change each object color on press of buton?
function multico() {
scene.traverse( function( tested ) {
for (let i=0; i<= tested.lengtht; i++){
console.log('tested');
};
so i got to use traverse to visit all geometry gltf
so i’m visibly wrong with tested.lenght its type is wrong
and after maybe some of you know to adress each ‘object.material’ to change it,
in the for loop?
like this that i got previously
object.material.color.set( Math.random() * 0xffffff );
but now into a ‘for’ in a ‘traverse’ , well its more harsh than expected. Cheers!
that’s a very subtle correction, if i may say so. You might have wanted to point out the initially wrong spelling of “length”, which had a surplus “t” at its end. I myself had to look more than twice until I realized that …
As per docs - you should not add / remove / modify any elements when using Object3D.traverse. If you need to do that - you can use children.forEach or save referenced to the elements you’d like to remove in an array outside of thetraverse callback.
function(){
var newMats = [];
//i add an array
scene.traverse(child => {
//i traverse
if ( child.isMesh ) {
if ( child.material )
//i found using 'push' to fill my array
newMats.push( { newMats: child.material.color, child : child} ); }});
//here i read my array is now full
newMats.forEach((element) => console.log(element));
for (var i = 0, n = newMats.length; i < n; i++){
newMats[i].object.color = material.color.set( Math.random() * 0xffffff );
}
};
//why my material is not defined ?
The .traverse thread you’ve linked does not really apply here, since you’re not modifying the order / count of children. Your entire function can be cleaned up and simplified to just:
No additional arrays or needUpdates necessary, just make sure this function is called after model is 100% loaded (keeping in mind that model loading is async.)
Yes i’ve use your snippet as is, thank you. It works as needed . Many thanks, it’s so satisfying, as you said Instead of color.set simply assign a new THREE.Color was the problem, and it did the trick. It’s a huge step