So I am trying to load a model in Threejs using GLTFLoader, the issue is that I want the model to be accessible even outside the model.
Example code:
let loader = new GLTFLoader();
loader.load("teeth.glb", function (glb) {
scene.add(glb.scene);
geometry = glb.scene;
let bounds = new THREE.Box3().setFromObject(geometry);
let size = bounds.getSize(new THREE.Vector3());
let { max } = Math;
let maxsz = max(size.x, max(size.y, size.z));
//Rescale the model..
geometry.scale.multiplyScalar(2.5 / maxsz);
geometry.updateMatrixWorld();
bounds.setFromObject(geometry);
geometry.position.sub(bounds.getCenter(new THREE.Vector3()));
});
console.log(geometry)
The issue is as soon as the loader block ends the geometry variable stats undefined rather than the 3d model properties.
Any help would be appreciated and I will be grateful.
The function is async, your model is not loaded (yet) when JS read console.log
So you need to either use the integrated callback, or create your own
example of a custom one: (for fun and tricks…this is probably not the classic way)
const gltfLoader = new GLTFLoader();
const meshArray = []; //array to store meshes
const modelUrl = [ //array of URLs
'./mesh/scene1.glb',
'./mesh/scene2.glb',
];
let count = modelUrl.length; //countdown
for (let i in modelUrl) { //loading loop
gltfLoader.load( modelUrl[i], function (gltf) {
const content = gltf.scene;
content.traverse( function ( child ) {
if ( child.isMesh ) {
meshArray.push(child);
count--
if (count === 0) { //draw all meshes when finished
for ( let j in meshArray ){
scene.add( meshArray[j] );
}
console.log("meshes loaded")
}
}
});
});
}