Unable to delete objects using Three.JS

I use Three.JS to make a plane and put boxes over it. Sometimes I need to delete all the boxes. So I am trying to do this with the following code:

for ( i = 0; i < scene.children.length; i ++ ) { var object = scene.children[ i ]; if ( object != plane && object != camera) { scene.remove(object); } } 

/ This kills every object that is not a plane or camera; -) /

It deletes some fields, but not all of them = (How to delete all fields? Greetings, Jose

+7
source share
3 answers

You need to go back to the front, not front to back, when deleting array objects like this.

 var obj, i; for ( i = scene.children.length - 1; i >= 0 ; i -- ) { obj = scene.children[ i ]; if ( obj !== plane && obj !== camera) { scene.remove(obj); } } 

What happens when you delete a node, everything after it is shifted. Say you delete scene.children [0]: children [1] will become new 0, 2 will become 1, etc. When moving from 0 to array.length, the for loop already moves and skips 1 node for each one you delete.

As an added plus, this should go a little faster, especially if you have a lot of objects, since scene.children.length gets only once, and not every loop.

+21
source

@Crazycatz answer is correct, but now we are in 2016, and instead of manual iteration, we can just call .slice() and .slice() over the array:

 scene.children.slice().forEach(obj => scene.remove(obj)) 

or without ES6 pluses:

 scene.children.slice().forEach(function(obj) { scene.remove(obj); }) 
+2
source

You must use! == instead of! = (its bit is faster). Did you try to go through your loop and check out the children of the scene after that? You may have added several cells to the plane as children that will not be deleted by this loop.

+1
source

All Articles