As I understand, GLTF loader is working asynchronous. What if I need to wait loading and then apply some code
var loader = new THREE.GLTFLoader();
var urlgltf = decodeURIComponent(container.dataset.url);
loader.load( urlgltf, function ( gltf ) {
model = gltf.scene;
scene.add( model );
}
model.dosomething();
I want to add something to model, but GLTF and new actions will be optional in my scene, so, I can’t add code inside load() function, I need it outside GLTF loader. Is any method to wait loading of GLTF loader, get access to all variables like model in example above?
yes, this is what I use now. But it’s working in animation loop, but I need something outside animation. For example, I want to add lights. And these lights must point to GLtF model if it’s existing and other object if model is not existing
Currently, I forced to build two functions - one for GLTF loader and second for context which is outside loader. It’s bad that we don’t have option to check if loader finished it’s job
You can use async/await. First, you need to convert the loader to return a promise:
Note: this is now build in for all loaders, use .loadAsync instead of load.
import { GLTFLoader } from '../../../vendor/three/examples/jsm/loaders/GLTFLoader.js';
const loader = new GLTFLoader();
// this utility function allows you to use any three.js
// loader with promises and async/await
function modelLoader(url) {
return new Promise((resolve, reject) => {
loader.load(url, data=> resolve(data), null, reject);
});
}
Then use it like this:
async function main() {
const gltfData = await modelLoader(URL),
model = gltf.scene;
scene.add(model);
dosomething(model);
}
main().catch(error => {
console.error(error);
});