How to remove everything loaded in an ISceneLoaderAsyncResult

I did some reading and learned that I should use Scene.dispose() to remove everything in a scene, but my assets are being loaded as ISceneLoaderAsyncResult and there is no such method on that interface.

const myLoadedGltf = await SceneLoader.ImportMeshAsync("", baseFilePath, filePath, this.scene);

// do stuff with the loaded asset

myLoadedGltf.dispose() // Property 'dispose' does not exist on type 'ISceneLoaderAsyncResult'.

Do I need to go through all meshes, skeletons etc and call dispose on them individually?

function disposeAsyncLoadedScene(sceneResult: ISceneLoaderAsyncResult) {
  sceneResult.meshes.forEach((item) => item.dispose());
  sceneResult.skeletons.forEach((item) => item.dispose());
  sceneResult.transformNodes.forEach((item) => item.dispose());
  sceneResult.lights.forEach((item) => item.dispose());
  sceneResult.geometries.forEach((item) => item.dispose());
  sceneResult.spriteManagers.forEach((item) => item.dispose());
  sceneResult.animationGroups.forEach((item) => item.dispose());
  sceneResult.particleSystems.forEach((item) => item.dispose());
}

Yeah this is not ideal but this is correct :frowning:

1 Like

Better use this construction, otherwise there will be some items left with forEach.

while (sceneResult.meshes.length) {
    sceneResult.meshes[0].dispose();
}
1 Like

Why is it that some items will be left when using forEach?

Here are some answers:

1 Like

When I tried to implement it with the while loop the page crashes. I logged out the result like this:

while (sceneResult.meshes.length > 0) {
    sceneResult.meshes[0].dispose();
    console.log(sceneResult.meshes);
  }

And it showed that the meshes were not being removed from the array. So do I have to pop them from the array and then call dispose?

while (sceneResult.meshes.length > 0) {
  sceneResult.meshes.pop()!.dispose();
}

Here is the example with a bit another approach - https://playground.babylonjs.com/#0VHCTL#212

1 Like

You can also try using LoadAssetContainerAsync. AssetContainer has a removeAllFromScene method that might be what you need.

PG: https://playground.babylonjs.com/#0VHCTL#213

1 Like

removeAllFromScene method doesn’t dispose the container assets (only removes them so they can be added later), but there is dispose method as well - https://playground.babylonjs.com/#0VHCTL#214

2 Likes