Tengo la siguiente función que usa un GLTF loader para cargar un modelo en la escena (importado de otra clase):
CreateMesh(path){ this.gltfLoader.load( path, (gltf) => { this.experience.scene.add(gltf.scene) } ) } Y llamo a esa función desde otra clase como esta, queriendo enviar a la matriz de jugadores (destinada a mantener las mallas de los jugadores) la malla gltf.scene devuelta por la función CreateMesh .
this.players.push(this.experience.loaderGltf.CreateMesh('./../static/player.glb')) Mi problema es que no puedo acceder a esa variable fuera de la función gltfLoader.load() como ves en el siguiente ejemplo:
CreateMesh(path){ let mesh = null this.gltfLoader.load( path, (gltf) => { this.experience.scene.add(gltf.scene) mesh=gltf.scene console.log(mesh) // prints gltf.scene } ) console.log(mesh) //prints "null" }Suponiendo que this.gltfLoader.load es asíncrono y aún no tiene una variante de devolución de promesa, manéjelo "prometiendo" esa función de estilo de devolución de llamada.
// return a promise that resolves the result of gltfLoader.load, or "gltf" async function loadMesh(path) { return new Promise(resolve => { this.gltfLoader.load(path, resolve); }); } // place this where loadMesh is imported and players is in scope... async createMesh() { let gltf = await loadMesh('some/path'); let mesh=gltf.scene; this.experience.scene.add(mesh); this.players.push(mesh); }La carga finaliza después de iniciar sesión fuera del cargador, así que intente algo como esto:
CreateMesh(path, callback){ let mesh = null this.gltfLoader.load( path, (gltf) => { this.experience.scene.add(gltf.scene) mesh=gltf.scene callback(mesh) } ) } CreateMesh('./../static/player.glb', console.log) // HooraaaaAgregar a la matriz:
this.experience.loaderGltf.CreateMesh('./../static/player.glb', (mesh) => this.players.push(mesh))