Search code examples
javascriptthree.jstypeerrortraversal

children[i] is undefined while removing object from the scene


I want to remove an object from the scene:

removeLegoByPos = (pos) => {
    this.scene.traverse((child) => {
        if (child.isGroup && child.userData.position) {
            if (child.userData.position.equals(pos)) {
                console.log(child.name);
                this.scene.remove(child);
            }
        }
    });
}

But I get an error:

lego_113

Uncaught TypeError: children[i] is undefined
    traverse three.module.js:7944

Can you please tell me how can I solve this issue? thanks in advance.


Solution

  • Possible Error
    a THREE.Group can have THREE.Mesh/Three.Object3D as its children so when you traverse and reach this group and remove it you remove its children, hence when the traverser goes to the next index it should be its child which was already removed.
    enter image description here below solution might fix it

    const removeLegoByPos = (pos) => {
        let LegoToBeRemoved = undefined
    
        this.scene.traverse((child) => {
            if (child.isGroup && child.userData.position) {
                if (child.userData.position.equals(pos)) {
                    LegoToBeRemoved = child
                    // since you found you group google if you can break the traverse, because I'm not sure if you can
                }
            }
        })
    
        if (legoToBeRemoved) {
            legoToBeRemoved.removeFromParent()
            return true
        }
    
        return false
    }