I'm currently using the THREE.js OBJ and MTL Loader in a loop to display various elements of a 3D animated cake. I specifically need these elements so that users can change the color of certain parts (e.g. decorations) of the cake.
However, I've noticed that every time I hit a THREE.load function, the loop execution is paused and it moves on to the next iteration (i++). As someone new to JavaScript, I'm unsure if I might be missing some basic understanding of loops.
It's only on the final iteration that the load function is called and executed correctly. If I run the same code without a loop, manually providing the material/object paths and using multiple loaders, everything works smoothly.
function draw(currentlySelectedCake){
layerArray = [];
// Load Cake
var i;
for (i = 0; i < currentCakeElements.length; i++){
if(currentCakeElements[i].endsWith(".mtl")){
var materialPath = "uploads/" +currentlySelectedCake + "/" + currentCakeElements[i];
var objectPath = "uploads/" +currentlySelectedCake + "/" + currentCakeElements[i+1];
var cakeLoader = new THREE.MTLLoader();
cakeLoader.load(materialPath, function (materials) {
materials.preload();
// Load the Cake
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.load(objectPath , function (object) {
layer1 = object.clone();
layer2 = object.clone();
layer3 = object.clone();
layer1.name = "Layer1Part" + i;
layer2.name = "Layer2Part" + i;
layer3.name = "Layer3Part" + i;
layer1.traverse((child) => {
if (child.isMesh) {
child.material = child.material.clone();
}
});
layer2.traverse((child) => {
if (child.isMesh) {
child.material = child.material.clone();
}
});
layer3.traverse((child) => {
if (child.isMesh) {
child.material = child.material.clone();
}
});
layer2.position.y = tortenhoehe;
layer3.position.y = tortenhoehe*2*0.75;
camera.lookAt(layer2.position);
layer1Group.add(layer1);
layer1Group.name = "Layer1";
layer2Group.add(layer2);
layer2Group.name = "Layer2";
layer3Group.add(layer3);
layer3Group.name = "Layer3";
});
layer1Elements.push(layer1Group);
layer2Elements.push(layer2Group);
layer3Elements.push(layer3Group);
});
}
});
}
}