I have the following function that uses a GLTF loader
to load a model into the scene (imported from another class):
JavaScript
x
10
10
1
CreateMesh(path){
2
this.gltfLoader.load(
3
path,
4
(gltf) =>
5
{
6
this.experience.scene.add(gltf.scene)
7
}
8
)
9
}
10
And I call that function from another class like this, wanting to push to the players array (meant to keep the players meshes) the gltf.scene mesh returned from the CreateMesh
function.
JavaScript
1
2
1
this.players.push(this.experience.loaderGltf.CreateMesh('./../static/player.glb'))
2
My problem is that I cannot access that variable outside the gltfLoader.load()
function as you see in the following example:
JavaScript
1
14
14
1
CreateMesh(path){
2
let mesh = null
3
this.gltfLoader.load(
4
path,
5
(gltf) =>
6
{
7
this.experience.scene.add(gltf.scene)
8
mesh=gltf.scene
9
console.log(mesh) // prints gltf.scene
10
}
11
)
12
console.log(mesh) //prints "null"
13
}
14
Advertisement
Answer
Assuming this.gltfLoader.load
is async and doesn’t already have a promise-returning variant, handle this by “promisifying” that callback-style function.
JavaScript
1
16
16
1
// return a promise that resolves the result of gltfLoader.load, or "gltf"
2
async function loadMesh(path) {
3
return new Promise(resolve => {
4
this.gltfLoader.load(path, resolve);
5
});
6
}
7
8
// place this where loadMesh is imported and players is in scope...
9
async createMesh() {
10
let gltf = await loadMesh('some/path');
11
let mesh=gltf.scene;
12
this.experience.scene.add(mesh);
13
this.players.push(mesh);
14
}
15
16