How to properly dispose of a mesh and remove it from a scene

EDIT: @Mugen87 has added a great guide to the docs on this topic: How to Dispose of Objects

I have seen several discussions of regarding related to this, but I am still unclear as to what the best approach is.

Suppose I have a mesh, consisting of a geometry and a material with several maps. Is the following sufficient?

myMesh.geometry.dispose();
myMesh.material.dispose();

scene.remove( myMesh );

Or do I need to go over all the material’s maps too and dispose of each individually?

Related question: scene.remove( myMesh ) dispatches a ‘removed’ event on myMesh - as far as I can see though this doesn’t actually do anything. Is it supposed to?

2 Likes

Hello looeee,

Assuming you want to completely remove your mesh (free up all memory), in addition to materials and geometry, you need to dispose the texture maps, the mesh object and the functions associated with it (i.e. animations). if the object is a grouped object, you will need to traverse down the object hierarchy and clean up all individual objects the same way.

You can use the “scene.remove” event to trigger the function call to clean up the specified mesh. It doesn’t do the clean up because a user may just want to remove the mesh from the scene and keep all in memory to add it again without having to reload. Each user has specific use cases and for example he/she may want to cleanup shaders attributes at the same time. This process flow may look tedious, but it allows for total control and flexibility. Plus, once you write the cleanup functions, it will be a done deal, because they will change rarely and can be reused into other projects.

2 Likes

You can use the “scene.remove” event to trigger the function call to clean up the specified mesh.

You mean that the “removed” event is intended as a hook to attach a custom cleanup function to?

The “removed” event is there to take any desired action right after the object3D is off the scene.

It could be used to load another object at the same position and be sure the 2 objects in question (the 1 removed & the 1 added) do not overlap on the scene. This maybe the case while working with large objects on slow platforms. Or it could trigger a function that has nothing to do with 3D, like update the score on a game, or all at once (cleanup, add, scoring & +)

Sorry to revive this old topic. Is there a sample anywhere of doing the required recursive traversal and cleanup of all resources? I just want to remove a sub-scene that I loaded from glTF.

Thanks to @Mugen87, there is now a comprehensive guide in the docs explaining everything to do with disposing of things:

How to Dispose of Objects

3 Likes