Disposing scene.meshes leaving last meshes?

Hello and happy new year everybody!

I have all what is around my card game done in vue.js, like the rooms where players are meeting before to start the game, and the game itself with babylonjs.

To speed-up everything, I preload babylonjs and my scene and make it invisible, when 4 players sit at a table, I just make the babylon scene visible, it is very quick. I’ll turn the scene invisible when people leave the game, and clean the specific content related to the last game, so I’ll never reload babylonjs…

Everything is working very well and very fast but I have some rare bugs with my cleaning function depending when a user will quit a game, like exactly while another player is playing a card…

So I was thinking at different approaches and thought that a very hard / effective one could be to remove all specifc meshes related to the game that was being left, in other words, I would like to start again a clear game looking exactly like what I preload at the beginning, so I traced scene.meshes.length right after everything is preloaded and was thinking I could do a cleaning function disposing any new meshes after that position…

I first tried to see if I was able to clean everything by looping on scene.meshes but was surprised it doesn’t remove the last meshes… I reproduced here on an previous playground I did, if you run it, pause, and click remove, I would expect to have everything disposed… am I wrong ?
https://www.babylonjs-playground.com/#J0ZJDX#15

Surprisingly, remaining meshes are disappearing after clicking the clear button several times.

Best

Cyril

Line 67. Every time you dispose of a mesh scene.meshes.length gets shorter so gets to 0 before all meshes are disposed of. Use while loop.

2 Likes

shame on me :slight_smile:

and thanks!

Something like that:

while(scene.meshes.length {
var mesh = scene.meshes[0]
console.log(mesh.name)
mesh.dispose();
}

thanks, I had to do several tries :slight_smile:
This works like a charm, as my clean state is based on the15 first meshes

clearMeshes : function (){
while(this.scene.meshes.length>15){
console.log("clearMeshes "+this.scene.meshes.length);
this.scene.meshes[this.scene.meshes.length-1].dispose();
}
},

From your code it seems that you dispose the 15 last meshes, not the first ones.
But if it works for you it is OK.
If you are going to reuse those meshes you may also make them invisible till you’ll need them again, instead of disposing.

removing last mesh until only the 15 first ones stay :slight_smile: