I have created a simple function for loading an object to the given scene and to return the object that gets added to the scene:
const _THREEJSHELPER = {
addObjectToScene: (scene, objString) => {
let loader = new GLTFLoader();
let obj = new THREE.Object3D(); // function seem to be returning this object for some reason
loader.load(objString, function (gltf) {
obj = gltf.scene;
scene.add(obj);
}, undefined, function (error) {
console.error(error);
});
return obj;
}
}
In the other js file when I am trying to use this function I am unable to get the actual object handle:
import _THREEJSHELPER from './src/threejs-helper';
let obj2 = _THREEJSHELPER.addObjectToScene(scene, 'models/object.glb');
obj2.position.x = 10; //This does not work for the object that that gets added
Am I missing any JavaScript concepts here? Or there is something else wrong with this ?
Appreciate any response.
You can’t write your code in a synchronous style. The function addObjectToScene() returns the newly created instance of Object3D. The reference to this instance will not change just because you assign gltf.scene to the local obj variable.