I'm currently working on manipulating an object loaded using OBJLoader in Three.js. The issue I'm facing is that while it's easy to manipulate the object once, I can't figure out how to do so during the animate loop or anywhere outside of the initial load callback.
Below is the code snippet:
function loadObject(path, name) {
var obj;
var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath(path);
mtlLoader.load(name + ".mtl", function(materials) {
materials.preload();
var objLoader = new THREE.OBJLoader();
objLoader.setMaterials(materials);
objLoader.setPath(path);
objLoader.load(name + ".obj", function(object) {
obj = object;
obj.position.x = 20;
scene.add(obj);
});
});
return obj;
}
var myObject = loadObject("assets/", "test");
myObject.position.y = 20;
Important points to consider are:
- I can load and manipulate the object within the loop without any errors;
- If I try to manipulate the object outside of the function, I encounter an error on the last line:
;Cannot read property 'position' of undefined
- Even if I define
obj
globally and then reference it accordingly, the same error persists.
I've also experimented with similar code using the JSON loader, but faced the same results (able to manipulate within the load, but not afterwards).