Creating instances dynamically at runtime (and disposing of them)

Hey there. This is my first post.

I have been goofing around with Babylon for the past 2 weeks and having fun putting together a game.
It’s been a great learning experience and the interactive playground is fantastic.

So I wanted to have a way to load an animated gltf/glb character models and to spawn a bunch of copies as needed. (Enemies, other players, etc.) Most of the examples unfortunately only showed how to instantiate some in the initial callback but I need more flexibility to create them on demand.

I found instantiateModelsToScene() which seems to do a fine job.

So next I found;
But I noticed when I dispose of the instances, they leave all kinds of stuff in memory.
Textures, Skeletons, Animation Groups, etc.
If I keep adding and deleting they just keep accumulating.
So I figured I must be doing something wrong.

Please see my example playground I just threw together.

Right clicking adds aliens to the scene and left clicking should dispose of them!


Welcome aboard!

I’m not sure you can automatically delete all resources linked to a mesh like skeletons as they can be shared with other meshes.

Adding @Deltakosh who will know for sure.

Hi Evgeni_Popov. Thank you for your response.

These resources are duplicates that get made during the instantiate.

I found a way (dirty hack) to manually dispose of the copied resources.
I keep an array of the instances/copies and loop over all of the animationGroups, rootNodes and skeletons and dispose them individually.

Please take a look at my new example playground.

It works fine in the playground version 4.2 although in 5.0.0 there is a texture that gets skipped and continues to accumulate as you keep adding/deleting more. Maybe a bug?


That’s because this mesh has morph targets: in 5.0, by default the morph target manager uses a texture to store the targets. So, you will need to dispose the morph target managers of the meshes to get rid of the accumulating textures.

Evgeni_Popov I see what you mean now about the morph targets.

Adding a pickResult.pickedMesh.morphTargetManager.dispose(); seems to dispose of the texture!

Now I can create instances and delete them as I like without leaking memory.

Thanks for your help.