Cannot read property 'traverse' of undefined when traverse object in scene and remove it

Des:
When I use Object3D.traverse to traverse object in the scene and remove it, I get an error:
image

Code

scene.traverse((item) => {
      if (item.isMesh) {
          this.meshes.remove(item);
          item.geometry.dispose();
          item.material.dispose();
      }
});

As per docs - you should not add / remove / modify any elements when using Object3D.traverse. If you need to do that - you can use children.forEach or save referenced to the elements you’d like to remove in an array outside of the traverse callback.

Note: Modifying the scene graph inside the callback is discouraged.

3 Likes

got it, thanks!