Adding metadata to mesh before adding mesh to scene

Hey all. I’m using scene.onNewMeshAddedObservable to listen for new meshes added to the scene, which is working well. Now I’m trying to add some metadata to the metadata of meshes when I add them:

this.mesh = Babylon.MeshBuilder.CreateCylinder(
    meshName,
    {
        height: 11.15, 
        diameter: 6, 
    }, 
    this.scene
);

this.mesh.metadata = { foo: 'bar' };

But the metadata isn’t available in my scene.onNewMeshAddedObservable callback. I assume this is because the mesh is added to the scene immediately when I call CreateCylinder, so the metadata hasn’t been added yet. Is there any way I can add this metadata so that it’s available in the observable callback?

Here’s a quick playground demonstrating what I’m trying to do: metadata on creation | Babylon.js Playground (babylonjs.com)

Some workarounds I’ve considered based on other forum posts:

  1. Create a 2nd “staging” scene where I initially add the mesh. Then add the metadata. Then move the mesh to the actual scene.
  2. Use AssetContainer to hold the mesh until the metadata exists, then move the mesh to the scene. But I don’t see a way to add a newly created mesh to the AssetContainer without first adding it to the scene. So the mesh would get added to the scene, then moved to the AssetContainer, the moved back to the scene.

Any other ways I could achieve this?

onNewMeshAddedObservable is called during mesh construction, meaning in the mesh constructor. So you won’t see anything in this callback that you add/modify to the mesh that comes after calling the constructor.

What you could do is adding the mesh in a “newly created mesh array” in onNewMeshAddedObservable and process this array afterwards (maybe in scene.onBeforeRenderObservable).

1 Like