Asynchronous issue with OBJLoader - wait for XHR t

2019-06-11 11:39发布

How can you make OBJLoader simply return the object rather than add it to the scene? I hit a synchronization problem where my code does not wait for the XHR request to finish, throwing errors.

The following example shows the problem:

var loader = new THREE.OBJLoader();

// return a mesh from an obj file   
function createObject( objFile, objName ) {
    object3d = loader.load( objFile , function ( object ) {
        object.name = objName;            
        console.log(object);
        return object;
    })
    return object3d;
}

car = createObject('path/to/car.obj', 'abc123');
car.position.y = 10;

This generates the following in console:

1. Uncaught TypeError: Cannot set property 'position' of undefined test.html:171
2. XHR finished loading: GET "path/to/car.obj". Three.js:11377
3. THREE.Object3D {id: 7, uuid: "9E8DC838-E68B-4FCA-A6AD-863D5D06D31F", name: "abc123", parent: undefined, children: Array[1]…}

So error (1) exists because 'car.position.x' happens while the XHR request is in progress and the object is null. My code doesn't wait. But (2) and (3) show that shortly after, load request does complete successfully.

Any ideas how I can make this work? How can I make createObject() wait until the XHR request is finished before continuing? Or is this generally just a bad way to sequence things?

1条回答
聊天终结者
2楼-- · 2019-06-11 12:19

You can create a "container" inside your method and add the object to that container once it loads.

var loader = new THREE.OBJLoader();

// return a mesh from an obj file   
function createObject( objFile, objName ) {
    var container = new THREE.Object3D();
    loader.load( objFile , function ( object ) {
        object.name = objName;
        container.add( object );
    })
    return container;
}

car = createObject('path/to/car.obj', 'abc123');
car.position.y = 10;
查看更多
登录 后发表回答