I am using the THREE.js OBJ and MTL Loader in an Loop to display different Elements of an 3d animated cake. I need those different Elements because I want the user to be able to change the color of those specific elements (eg. the decor) of the cake.
But whenever I hit a THREE.load function the execution of the iteration of the loop is stopped an it starts with the next (i++). I am new to Javascript. So I am not sure if I am missing an general understanding of loops.
Only in the last gothrough the load function is called and correctly executed. If I use the exact same code without a loop, but rather provide the material-/objectPath hard coded and use several loader everything runs fine.
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);
});
}
});
}
}
I think this here was my solution. Still in the final process of testing. But looking good so far.
https://www.albertgao.xyz/2016/08/25/why-not-making-functions-within-a-loop-in-javascript/
i and j gets declared firsti which is not in its scopei accumulates to 3 since the loop runs for 3 times.i, and it found there is no i inside.i, in the global scope, still within its lexical scope, which is totally legitimate for this anonymous function to refer.i is 3. We solved it in step 4.3 will be output.