How to Clear a Three.js Scene and Remove All Children
In Three.js, managing memory and scene states is crucial for
maintaining application performance. This article explains how to use
the built-in scene.clear() method to efficiently remove all
child objects, lights, and cameras from a Three.js Scene, resetting it
back to an empty state.
The scene.clear() Method
The Scene class in Three.js inherits from
Object3D. In modern versions of Three.js (r123 and later),
Object3D includes a native .clear() method.
Calling this method on your scene instance will remove all of its child
elements in a single operation.
// Initialize your scene
const scene = new THREE.Scene();
// ... add meshes, lights, and cameras to the scene ...
// Clear the scene
scene.clear();When you call scene.clear(), Three.js loops through the
scene.children array and detaches every object.
Important: Handling GPU Memory Disposal
While scene.clear() successfully detaches all child
objects from the scene graph so they are no longer rendered, it
does not automatically free up the GPU memory allocated
for their geometries, materials, or textures. To prevent memory leaks,
you must manually dispose of these resources before clearing the
scene.
Here is the recommended workflow to safely reset your scene and free up memory:
function clearScene(scene) {
scene.traverse((object) => {
if (!object.isMesh) return;
// Dispose geometry
if (object.geometry) {
object.geometry.dispose();
}
// Dispose material(s)
if (object.material) {
if (Array.isArray(object.material)) {
object.material.forEach((material) => material.dispose());
} else {
object.material.dispose();
}
}
});
// Remove all objects from the scene
scene.clear();
}Alternative: Manual Removal (For Older Three.js Versions)
If you are working with an older version of Three.js that does not
support the .clear() method, you can achieve the same
result by manually looping through the children array backwards and
using .remove():
while(scene.children.length > 0){
scene.remove(scene.children[0]);
}Using scene.clear() is the most direct, modern, and
readable way to reset your Three.js scene state, provided you pair it
with proper asset disposal.