It appears that there are a few issues with the code provided. However, one key problem seems to be related to the outdated async
issue. The loaders in use function asynchronously, meaning that the execution of the code happens at a later time, while the current code assumes synchronous behavior. As a result, all the fences end up reading the value
when the looping is completed, leading to delayed triggers. Below is a refactored version of the function to address this behavior:
function generateFence(nb){
// Initially loading the model once as it will be reused.
// Wrap it in a promise for future reference.
const value = -5;
const fences = new THREE.Group;
const model = new Promise(function( resolve ){
THREE.ColladaLoader( loadingManager ).load( 'fence/model.dae', resolve );
});
// Use `let` declaration for accurate looping values
// even during asynchronous operations.
for( let i = 0; i < nb; i++ ){
// Async operation after `then`, ensuring loaded model usage.
model.then(model => {
// Clone the model to create multiple instances
const fence = model.scene.clone();
// Calculate x position based on value and i's state
fence.position.set( value + i * 3, 0, -5 );
fences.add( fence );
});
}
return fences;
}
// Returns a THREE.Group. Adds loaded fences to a hidden scene group.
scene.add( generateFence(3) );
The main issue likely stems from identical fences due to async actions, causing all to be positioned similarly and appear as one.