Scene.meshes is not returning all the meshes

I want to dispose all the meshs in the scenes and reload with new set of meshes

i am doing this, but the it is not disposing all the all the meshes in the scene, is there some thing wrong i am doing

for (var k = 0; k < scene.meshes.length; k++) {
var mesh = scene.meshes[k]
console.log(mesh.name)
mesh.dispose(false,true);
}

By doing this you are reducing the size of scene.meshes so your loop will not work :slight_smile:
something like that will be better:

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

I tried looking into this with a For/Of loop and got the same result as (or probably similar to) @Krishna_Kishore.

I logged the scene.meshes.length after each loop and was left with 2. This matched the number of meshes still visible in the scene. Is this happening because the loop already passed over the first two items in the list, and then items 4 and 5 became the new 1 and 2?

P.S. @Deltakosh’s While loop definitely worked, I’m just not sure why the other loops aren’t working.

Let’s say there are 5 meshes.

(after each iteration (i+1) you remove one mesh, so mesh.length = mesh.length - 1)

1 => i = 0; meshes.length = 5; 0 < 5 true
2 => i = 1; meshes.length = 4; 1 < 4 true
3 => i = 2; meshes.length = 3; 2 < 3 true
4 => i = 3; meshes.length = 2; 3 < 2 not true -> loop stops.

So for 5 meshes you get 3 iterations of dispose, 3 meshes are disposed, 2 meshes stayed in the scene.

3 Likes