How do I clear THREE.JS Scene

戏子无情 提交于 2020-08-22 09:29:46

问题


I am trying to find ways of clearing all the objects in a scene without destroying the scene itself. I know that naming the object is one way and then when we want to delete the object, we just "get" it by its name. However, I want to find a quick way to clear a scene of all the objects in it, regardless of their names. Is there a easy way to do it? Thanks!


回答1:


You can traverse the child objects of the scene and remove them one by one.


scene.children.forEach(function(object){
    scene.remove(object);
});

Edit:

As suggested in the comments, the above answer is wrong. The correct way to remove all objects from the scene is using a for/while loop.

while(scene.children.length > 0){ 
    scene.remove(scene.children[0]); 
}

Note: This is just a quick and dirty clearing of the object hierarchy. If you plan on doing this a lot you risk running in to memory leaks with the code above because the renderer has references to the objects materials, textures and geometries. A complete clean of the scene is more complicated and there are plenty other questions that goes in to more detail:

  • Three.js Collada - What's the proper way to dispose() and release memory (garbage collection)?
  • THREE js proper removing object from scene (still reserved in HEAP)
  • Deallocating heap objects when removing mesh from scene



回答2:


I have a more concise way of doing this. I noticed that the remove method of Object3D accepts more than one parameter for object removal. This allows us to use the entire children array by modifying the call to use each element as individual parameters by taking advantage of the built-in apply method for functions. This works like so:

scene.remove.apply(scene, scene.children);



回答3:


Traversing all children and call dispose on their geometry, material and texture. The code below is my solution.

function clearThree(obj){
  while(obj.children.length > 0){ 
    clearThree(obj.children[0])
    obj.remove(obj.children[0]);
  }
  if(obj.geometry) obj.geometry.dispose()

  if(obj.material){ 
    //in case of map, bumpMap, normalMap, envMap ...
    Object.keys(obj.material).forEach(prop => {
      if(!obj.material[prop])
        return         
      if(obj.material[prop] !== null && typeof obj.material[prop].dispose === 'function')                                  
        obj.material[prop].dispose()                                                        
    })
    obj.material.dispose()
  }
}   

clearThree(scene)


来源:https://stackoverflow.com/questions/30359830/how-do-i-clear-three-js-scene

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!