Threejs remove all together object from scene
A preferred method is using the scene's traverse
function. All objects have this function and will do a depth-first search through the parent's children.
Here's a snippet from Mr. Doob himself.
scene.traverse( function ( object ) {
if ( object instanceof THREE.Mesh ) {
var geometry = object.geometry;
var matrixWorld = object.matrixWorld;
...
}
});
And here's a bit from r82's source:
traverse: function ( callback ) {
callback( this );
var children = this.children;
for ( var i = 0, l = children.length; i < l; i ++ ) {
children[ i ].traverse( callback );
}
}
You can also use traverseVisible
in your case:
scene.traverseVisible(function(child) {
if (child.type !== 'Scene') {
scene.remove(child);
}
});
You have to do the opposite:
for( var i = scene.children.length - 1; i >= 0; i--) {
obj = scene.children[i];
scene.remove(obj);
}
because in each iteration the .children
array changes once you do a .remove()
from the start and the indexing of that array changes.
If you want to understand it better, unroll the for loop and follow what the index into the array is.
You can accomplish that with while :
while (object.children.length)
{
object.remove(object.children[0]);
}
Explanations :
object.children.length return true if object.children.length is not 0, if it's equal to 0 it return false.
So you just have to remove the first child element as long as object has children.