var hero;
BABYLON.SceneLoader.ImportMesh("hero", "./scenes/", "girl.glb", scene, function (newMeshes, particleSystems, skeletons, animationGroups) {
hero = newMeshes[0];
//this can read variables outside ImportMesh() but cannot give them value after the end bracket.
});
//error here because hero is undefined
hero.position = new BABYLON.Vector3(3.7,-5,-10);
hero.ellipsoid = new BABYLON.Vector3(0.5, 1.0, 0.5);
hero.ellipsoidOffset = new BABYLON.Vector3(0, 1.0, 0);
scene.gravity = new BABYLON.Vector3(0, -0.9, 0);
Hi @fire7side, this is because ImportMesh is fundamentally an asynchronous operation – it takes some time to complete, and the browser can’t hang around forever waiting for it to complete – so the ImportMesh function is immediately evaluated and the program continues to run.
You have two options.
- Put your code that relies on
hero
inside the callback - Make your function
async
(which means it returns a Promise) and await the result. There is a separate API for this path called “ImportMeshAsync” (in general any scene loader operations have an ^Async version).
1 would look like this:
BABYLON.SceneLoader.ImportMesh("hero", "./scenes/", "girl.glb", scene, function (newMeshes, particleSystems, skeletons, animationGroups) {
hero = newMeshes[0];
hero.position = new BABYLON.Vector3(3.7,-5,-10);
hero.ellipsoid = new BABYLON.Vector3(0.5, 1.0, 0.5);
hero.ellipsoidOffset = new BABYLON.Vector3(0, 1.0, 0);
});
scene.gravity = new BABYLON.Vector3(0, -0.9, 0);
(2) would look like this (you have to make the calling function async as well):
const res = await BABYLON.SceneLoader.ImportMeshAsync("hero", "./scenes/", "girl.glb", scene);
const hero = res.meshes[0];
hero.position = new BABYLON.Vector3(3.7,-5,-10);
hero.ellipsoid = new BABYLON.Vector3(0.5, 1.0, 0.5);
hero.ellipsoidOffset = new BABYLON.Vector3(0, 1.0, 0);
scene.gravity = new BABYLON.Vector3(0, -0.9, 0);
Not used the ImportMeshAsync API so my understanding of the object it resolves to may be slightly wrong. But the principle is correct.
Thanks. I got the first method to work, if I made hero = null; in the main part and then put a condition to render it only if it wasn’t null in the render loop, otherwise I just got an error there. I’m going to check out the async also.