Created
October 17, 2023 05:49
-
-
Save taitems/0537b6119ffe762b4a773ea8fbb4f8dd to your computer and use it in GitHub Desktop.
Recursive three.js scene cleanup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as THREE from 'three'; | |
export const cleanup3dObject = function (obj) { | |
if (obj instanceof THREE.Object3D || obj instanceof THREE.Scene) { | |
// Dispose of all children | |
obj.traverse(function (child) { | |
if (child instanceof THREE.Mesh || child instanceof THREE.SkinnedMesh) { | |
// Dispose of the geometry and material to release resources | |
child.geometry.dispose(); | |
if (child.material instanceof THREE.Material) { | |
child.material.map?.dispose(); | |
child.material.dispose(); | |
} else if (Array.isArray(child.material)) { | |
// Handle multiple materials if applicable | |
child.material.forEach(function (material) { | |
material.map?.dispose(); | |
material?.dispose(); | |
}); | |
} | |
} | |
if (child.children && child.children.length) { | |
for (let i = 0; i < child.children.length; i++) { | |
cleanup3dObject(child.children[i]); | |
} | |
} | |
}); | |
// Dispose of the object/scene itself | |
obj.traverse(function (child) { | |
child?.geometry?.dispose(); | |
if (child.material) { | |
let arr = [] | |
if (child.material instanceof Array) { | |
arr.push(...child.material); | |
} else { | |
arr.push(child.material); | |
} | |
arr.forEach(function (mtrl) { | |
mtrl?.map?.dispose(); | |
mtrl?.lightMap?.dispose(); | |
mtrl?.bumpMap?.dispose(); | |
mtrl?.normalMap?.dispose(); | |
mtrl?.specularMap?.dispose(); | |
mtrl?.envMap?.dispose(); | |
mtrl.dispose(); | |
}); | |
} | |
}); | |
// Clear the object/scene's children | |
obj.children.length = 0; | |
// Optionally, remove the object/scene from its parent | |
if (obj.parent) { | |
obj.parent.remove(obj); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment