There is a way to import mesh synchronously?

Hi,

I need to import mesh synchronoulsy to do something with the mesh after.
I already try ImportMesh without expected effect.

To example i have this following code

main.js :

let obj = new Obj_Asset(objName, filePath, fileNameWithExtension);
obj.loadObj(babylonPositionXYZ);
// do something with obj.mesh, for example the folowing console.log
console.log(obj.mesh);  // currently return undefined

Obj_Asset :

class Obj_Asset {
  constructor (objName, filePath, fileNameWithExtension) {
    this.mesh = undefined
    this.objName = objName
    this.filePath = filePath
    this.fileNameWithExtension = fileNameWithExtension
  }

  loadObj(positionXYZ) {
    BABYLON.SceneLoader.ShowLoadingScreen = false;

    let importedMeshes = BABYLON.SceneLoader.ImportMesh(null, this.filePath, this.fileNameWithExtension, scene);

    this.mesh = BABYLON.Mesh.MergeMeshes(importedMeshes.meshes, true, true, undefined, false, true);
  }
}

I don’t want to put make loadObj async and put an await on ImportMesh, it force me to put an await on obj.loadObj on main an a asyn on his parent function, so it force me to put an await to… bla… bla… bla…

did someone have an idea ?
thanks by advance

Is this topic from the old forum of any use?

https://www.html5gamedevs.com/topic/32480-loading-asynchronous-objects-into-array-for-later-use/?do=findComment&comment=187590

1 Like

Hi VerandaLouis,

Formally, I believe the answer to the question “Is it possible to load a mesh synchronously?” is, “No, not really.” If I’m understanding this correctly, this is because of the way JavaScript works: synchronous in this sense means blocking, and because loading a mesh can involve operations that leave JavaScript and then have to come back, blocking becomes problematic. I know adding asynchrony will have cascading effects, but I really think it’s much better to embrace asynchrony early on and design around it. Because it’s a reality of JavaScript and Web code, this situation will keep popping up, and without a solid asynchrony pattern it’s going to be a fight every time.

Something like that. (use async and await)

the MergeMesh function will be executed after the file is imported

async loadObj(positionXYZ) {
    BABYLON.SceneLoader.ShowLoadingScreen = false;

    let importedMeshes = await BABYLON.SceneLoader.ImportMesh(null, this.filePath, this.fileNameWithExtension, scene);

	if(importedMeshes)
		this.mesh = BABYLON.Mesh.MergeMeshes(importedMeshes.meshes, true, true, undefined, false, true);
}
1 Like