José José - 8 months ago 62
Javascript Question

Cant remove objects using Three.JS

I'm using Three.JS to make a plane and put some boxes over it
I need remove all boxes sometimes. So I'm trying to do it with the following code:

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

/This kill each object that is not the plane or the camera ;-)/

It deletes some boxes, but not all of them =(
How can I delete all boxes?
Greetings, José

Answer Source

You need to go back to front, not front to back, when removing 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) {

What is happening is when one removes a node, all the ones after it shift. Let's say you remove scene.children[0]: children[1] will become the new 0, 2 will become 1, etc. When going from 0 to array.length, the for loop has already moved on and is skipping 1 node for every one you delete.

As an additional plus, this should go slightly faster, especially if you have many objects, since scene.children.length is only gotten once, instead of every loop.