How do I clear THREE.JS Scene
You can traverse the child objects of the scene and remove them one by one.
As suggested in the comments, this should be done in reverse order to not modify the elements that you're iterating over.
while(scene.children.length > 0){
scene.remove(scene.children[0]);
}
Note: This is just a quick and dirty clearing of the object hierarchy. If you plan on doing this a lot you risk running in to memory leaks with the code above because the renderer has references to the objects materials, textures and geometries. A complete clean of the scene is more complicated and there are plenty other questions that goes in to more detail:
- Three.js Collada - What's the proper way to dispose() and release memory (garbage collection)?
- THREE js proper removing object from scene (still reserved in HEAP)
- Deallocating heap objects when removing mesh from scene
I have a more concise way of doing this. I noticed that the remove
method of Object3D accepts more than one parameter for object removal. This allows us to use the entire children
array by modifying the call to use each element as individual parameters by taking advantage of the built-in apply
method for functions. This works like so:
scene.remove.apply(scene, scene.children);