Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clear THREE.JS Scene

Tags:

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!

like image 205
ExtremelySeriousChicken Avatar asked May 20 '15 20:05

ExtremelySeriousChicken


2 Answers

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:

like image 123
micnil Avatar answered Sep 30 '22 01:09

micnil


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);
like image 39
Jonathan Gray Avatar answered Sep 30 '22 01:09

Jonathan Gray