I have an app where I am loading glb models, user can see one model at a time and switch between different models. But after switching between models few times I get this error. I am disposing previous model as I load the new one and so on. is it memory leak issue? or something else. I am disposing all the entities of model by using dispose method, eg. mesh.dispose(true, true) for all meshes
Hey! Welcome!
You should use:
mesh.dispose(false, true)
to recursively dispose the node.
Pay attention to the first parameter. It’s a bit tricky. It’s called doNotRecurse
so you have to set it to false
for recursive disposal of all children nodes.
Here is small PG loading and disposing two meshes in a loop, no issues at all.
so I was looping through all the meshes and disposing them one by one and thats why I was keeping the first arg as true, and Initially I tried the same way as shown in playground and had the same issue.
It’s hard to tell what’s going wrong without seeing your code.
However, you can try this simple approach:
- Disable the nodes (meshes or transform nodes) you want to delete by calling
setEnabled(false)
on each one. - Collect all these nodes in an array, e.g.,
toDelete.push(node)
. - Loop through the array and dispose of each node:
for (const n of toDelete) { n.dispose(false, true); }
You can also add sanity check for disposed nodes:
for (const n of toDelete) { !n?.isDisposed() && n.dispose(false, true); }
- Clear the array afterward:
toDelete.length = 0;
This ensures all disposals happen in a single “transaction.”
You can totally level this up by throwing all that into a safeDelete
function — clean & reusable.
Yeah, I understand. though can’t really share the code. Will try this and if same issue persists I will try to reproduce it in code sandbox. Thanks
Another option is to load models with LoadAssetContainerAsync
-
Babylon.js docs
And then just dispose()
the AssetContainer - Babylon.js docs - to dispose all the assets in the container.