Three.js Loader callback issues in loop - only receive last value?

非 Y 不嫁゛ 提交于 2020-01-06 17:57:05

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!