spite / THREE.MeshLine

Mesh replacement for THREE.Line
MIT License
2.16k stars 380 forks source link

scene.remove doesn't work? #10

Closed dhritzkiv closed 8 years ago

dhritzkiv commented 8 years ago
//100 MeshLines have been added to a scene
//then I want to delete all of them from the scene:

scene.children.forEach(function(child) {
    scene.remove(child);
});

//only 50 are removed
//running it again
//only 25 are removed
//running it again
//only 13 are removed (see a pattern?)

The same result occurs with for loops and using scene.traverse. However, doing this:

scene.children.splice(0);

…does work. Weirdness. Try opening the main demo and copying+pasting the above pieces of code to see the results.

Am I doing something incorrectly?

r73

spite commented 8 years ago

I'd definitely say using Array.forEach in the array you're modifying by removing items might yield some counterintuitive (but correct) results. Try with an old and tried while():

`while( scene.children.length ) scene.remove( scene.children[ 0 ] )``

Also, remember that this would remove everything added to the scene: meshes, lights, helpers... You'd better keep an array of elements you want to remove at some point.

dhritzkiv commented 8 years ago

using Array.forEach in the array you're modifying by removing items…

duh, of course!

this would remove everything added to the scene

yep. my plan was to use an if statement to only remove MeshLines.

Anyway, I ultimately achieved it using filter (to create a copy) and forEach to then remove the objects:

scene.children
.filter(child => child.type === "Mesh")
.forEach(scene.remove, scene);