My current dilemma involves working with an object that I've loaded using THREE.ObjectLoader()
. This object consists of various elements, resembling a simple box made up of panels and sticks.
My goal is to assign different textures to specific child objects within this loaded object.
However, I'm encountering a problem where all the textures of the object (material.map
) are being overwritten by the last texture set in the loop. Here's an example of the code:
var objectLoader = new THREE.ObjectLoader();
objectLoader.load("carport-scene-nocolor.json", function ( object ) {
var textureLoader = new THREE.TextureLoader();
var glass = textureLoader.load('glass2.jpg');
var crate = textureLoader.load('crate.gif');
object.traverse( function ( child )
{
child.receiveShadow = true;
child.castShadow = true;
if ( child instanceof THREE.Mesh ) {
console.log(child.name);
child.material.shininess = 100;
child.material.wireframe = false;
child.material.normalScale = new THREE.Vector2( 1, 1 );
if( child.name === 'wooden_slats3' ) {
child.material.map = glass;
child.material.needsUpdate = true;
} else {
child.material.map = crate;
child.material.needsUpdate = true;
}
}
});
object.position.y = -1;
object.position.x = 0;
object.receiveShadow = true;
object.castShadow = true;
scene.add( object );
scene.fog = new THREE.Fog( 0xffffff, 50, 100 );
} );
Upon inspecting the console output, I noticed that the last element in the traverse loop is named 'wooden_slats4'. Despite expecting 'wooden_slats3' to have a 'glass' texture, all elements end up with the 'crate' texture map.
Attempting to modify the if statement to child.name === 'wooden_slats4'
only results in all objects being assigned that texture, as it's the last child in the object.
While I initially suspected an issue with how object.traverse
functions, my research indicates that my approach is sound.
For your reference, the console output shows:
pCube1
pCube2
pCube3
pCube4
wooden_slats2
wooden_slats3
wooden_slats4
Any assistance would be greatly appreciated.