Cant remove objects using Three.JS

11,523

Solution 1

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) {
        scene.remove(obj);
    }
}

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.

Solution 2

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

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

or without ES6 goodies:

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

Solution 3

You should use !== instead of != (its a bit faster). Did you tried to step through your loop and check scene children after that? Maybe you added some boxes to the plane as childs which will not be deleted by this loop.

Share:
11,523
José
Author by

José

@joseespinadote

Updated on July 14, 2022

Comments

  • José
    José almost 2 years

    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) {
            scene.remove(object);
        }
    }
    

    /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é