问题
I need to load model in loop, the results I want to achieve is the first model with material[0], the second model with material[1]...
But my results are all models have the final material. I think because when the function create mesh got called so variable "i" is already in the last value.
I came across Closure in loop question, but does not seem to apply.
Any help?
Here the code:
var loader = new THREE.CTMLoader();
var material = [new THREE.MeshLambertMaterial( { color: 0xffaa00 } ),
new THREE.MeshLambertMaterial( { color: 0xffffff } )]
for (i = 0; i < material.length; i++) {
loader.load( "models/ctm/ben.ctm", function( geometry ) {
var mesh = new THREE.Mesh( geometry, material[i] );
scene.add( mesh );
}, { useWorker: true } );
}
回答1:
Put the action to the function:
function addToScene (material) {
var loader = new THREE.CTMLoader();
var mesh;
loader.load( "models/ctm/ben.ctm", function( geometry ) {
mesh = new THREE.Mesh( geometry, material );
}, { useWorker: true } );
scene.add(mesh)
}
var material = [new THREE.MeshLambertMaterial( { color: 0xffaa00 } ),
new THREE.MeshLambertMaterial( { color: 0xffffff } )]
for (material.length; i++) {
addToScene (material[i]);
}
来源:https://stackoverflow.com/questions/29456674/three-js-loader-callback-issues-in-loop-only-receive-last-value