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?
You can create a "container" inside your method and add the object to that container once it loads.