【问题标题】:Asynchronous issue with OBJLoader - wait for XHR to finish loadingOBJLoader 的异步问题 - 等待 XHR 完成加载
【发布时间】:2023-03-24 12:25:01
【问题描述】:

如何让 OBJLoader 简单地返回对象而不是将其添加到场景中?我遇到了一个同步问题,我的代码没有等待 XHR 请求完成,从而引发错误。

下面的例子说明了问题:

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;

这会在控制台中生成以下内容:

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]…}

因此存在错误 (1),因为在 XHR 请求正在进行且对象为空时发生了“car.position.x”。我的代码不等待。但是 (2) 和 (3) 表明不久之后,加载请求确实成功完成了。

有什么想法可以让我完成这项工作吗?如何让 createObject() 等到 XHR 请求完成后再继续?或者这通常只是一种不好的排序方式?

【问题讨论】:

    标签: javascript ajax asynchronous three.js


    【解决方案1】:

    您可以在方法中创建一个“容器”,并在加载后将对象添加到该容器中。

    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;
    

    【讨论】:

    • 太棒了。谢谢!
    猜你喜欢
    • 2020-10-04
    • 2019-05-31
    • 2019-06-16
    • 2018-03-05
    • 2021-10-11
    • 1970-01-01
    • 2018-12-09
    • 2014-04-03
    • 1970-01-01
    相关资源
    最近更新 更多