首页 > 解决方案 > How can I load a group of objects to a global variable with OBJLoader without type-error messages?

问题描述

I'm using the following code to load OBJ objects, but in order to load the resulted group on a global variable, I pre-define the variable as 'null' which raises Type-error messages in Firefox console. I tried defining it as THREE.Group, THREE.Mesh, etc to no avail -those are causing the code to not execute. How can I have the same functionality without those annoying error messages?

Firefox developer tools

//this is causing Type-error messages in FF dev tools
var femModel = null;

var onProgress = function ( xhr ) {
    if ( xhr.lengthComputable ) {
        var percentComplete = xhr.loaded / xhr.total * 100;
        console.log( Math.round(percentComplete,2)+ '% downloaded');//<<<<
    }
    if (percentComplete = 100){
        waitmodeltoload();//<<<<<<
    }
};

var onError = function ( xhr ) { }; 

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'female02/' );


mtlLoader.setMaterialOptions({ side:THREE.DoubleSide });

// the code in question:
mtlLoader.load( 'female02.mtl', function( materials ) {

        materials.preload();
        var objLoader = new THREE.OBJLoader();
        objLoader.setMaterials( materials );
        objLoader.setPath( 'female02/' );
        objLoader.load( 'female02.obj', function ( object ) {

        femModel = object;

        }, onProgress, onError );
});

var waitid;
function waitmodeltoload(){
    if (!femModel){
        clearTimeout(waitid);
        waitid = setTimeout(setupmodel, 100);
    }
    setupmodel();//<<<<<
}

function setupmodel(){
    var intersects=null;
    femModel.traverse( function ( child ) {   // <<<<<<<<
        if ( child instanceof THREE.Mesh ) {
            child.castShadow = true;
            child.receiveShadow = true; 
        }           
    } );    
    femModel.position.set( 0, -90, 0 );
    sceneR2S.add( femModel );

}

标签: three.jsglobal-variablestypeerrorobjloader

解决方案


好的,这比我想象的要简单,这是我的逻辑错误,我忽略了代码在它可用之前试图访问 femModel:

所以而不是:

var waitid;
function waitmodeltoload(){
    if (!femModel){
        clearTimeout(waitid);
        waitid = setTimeout(setupmodel, 100);
    }
    setupmodel();
}

它应该是:

var waitid;
function waitmodeltoload(){
    if (!femModel){
        clearTimeout(waitid);
        waitid = setTimeout(setupmodel, 100);
    }else{
        setupmodel();
    }
}

在第一种情况下,即使没有加载模型,也会调用 setupmodel()。只需要一个“else”——不再需要红色警​​报类型错误消息。


推荐阅读