0

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 } );

}
Community
  • 1
  • 1
Ben Mack
  • 489
  • 2
  • 7
  • 29
  • dont you forget to put the mesh to the scene? scene.add(mesh)? – Martin Apr 05 '15 at 11:21
  • Edited, just forgot to add to the clear code for question :) – Ben Mack Apr 05 '15 at 11:24
  • I think you don't get a function example purpose. You first must load a geometry and materials, after put materials on geometry, that will create mesh. After you can put mesh to the scene. What you are doing is to load geometry and put it to the scene in part where is material created. – Martin Apr 05 '15 at 11:30

1 Answers1

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]);

}
Martin
  • 2,575
  • 6
  • 32
  • 53