I am trying to find ways of clearing all the objects in a scene without destroying the scene itself. I know that naming the object is one way and then when we want to delete the object, we just "get" it by its name. However, I want to find a quick way to clear a scene of all the objects in it, regardless of their names. Is there a easy way to do it? Thanks!
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:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With