【发布时间】:2021-11-27 02:11:12
【问题描述】:
我有以下函数,它使用GLTF loader 将模型加载到场景中(从另一个类导入):
CreateMesh(path){
this.gltfLoader.load(
path,
(gltf) =>
{
this.experience.scene.add(gltf.scene)
}
)
}
我从另一个类似的类中调用该函数,希望将 CreateMesh 函数返回的 gltf.scene 网格推送到玩家数组(意在保持玩家网格)。
this.players.push(this.experience.loaderGltf.CreateMesh('./../static/player.glb'))
我的问题是我无法在 gltfLoader.load() 函数之外访问该变量,如下例所示:
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"
}
【问题讨论】:
-
它看起来像一个异步函数。网格在日志点未定义,因为初始化它的函数尚未运行。
-
这是同步和异步代码执行的问题。尝试在您的第二个 console.log 周围使用
setTimeout并查看您的问题。为什么需要在加载后立即访问mesh?
标签: javascript three.js