Skip to content

Instantly share code, notes, and snippets.

@HoraceShmorace
Created January 1, 2022 23:20
Show Gist options
  • Save HoraceShmorace/5041e4f1392c16987a4215b70c89af13 to your computer and use it in GitHub Desktop.
Save HoraceShmorace/5041e4f1392c16987a4215b70c89af13 to your computer and use it in GitHub Desktop.
Disposes of any Three.js object and any disposal objects in the hierarchy below it by doing a depth-first search
/**
* Disposes of any Three.js object (mesh, material, etc.) and any disposable objects in the hierarchy below it by doing a depth-first search.
* @param {Boolean} showLogging Output logs useful for troubleshooting.
* @example
* const trash = HierarchyDisposal(true)
* trash([some three.js object])
*/
function HierarchyDisposal (showLogging = false) {
const bag = []
const ignoreKeys = [
'_super',
'parent'
]
const dispose = (obj, ondone) => {
const id = obj.uuid
const name = obj.name || id || obj
if (bag.includes(id)) return
if (showLogging) console.log('calling dispose on', name)
for (var key in obj) {
const childObj = obj[key]
if (
obj.hasOwnProperty(key) &&
!ignoreKeys.includes(key) &&
childObj &&
typeof childObj === 'object'
) dispose(childObj)
}
if (typeof obj.dispose === 'function' && obj.uuid) {
if (showLogging) console.log('disposing of', name)
obj.dispose()
bag.push(id)
}
if (typeof ondone === 'function') ondone(bag)
}
return dispose
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment