THREE js proper removing object from scene (still reserved in HEAP)

前端 未结 1 443
终归单人心
终归单人心 2020-12-08 16:34

What is the proper way to remove mesh form scene? In this example:

    removable_items = [];
    box = new THREE.Object3D();
    scene.add(box);

    functio         


        
相关标签:
1条回答
  • 2020-12-08 17:26

    I've done a few experiments and i think there is nothing really wrong with your code. One thing that i've learned though, is that that garbage collector might not run exactly when you think it does. Just in case, I wrapped your code in a IIFE (good practice but not necessary in this case) and expected the heap to be cleared as soon as the function finished running and went out of scope. But it actually took some time for it to clear:

    So i thought, okey, thats not to good, what if i was creating more objects in that timespan where the garbage collector is just lingering, so i did:

    .
    .
    makeExperiment(50);
    clean();
    makeExperiment(50);
    clean();
    makeExperiment(50);
    clean();
    makeExperiment(50);
    clean();
    makeExperiment(50);
    clean();
    makeExperiment(50);
    clean();
    makeExperiment(50);
    clean();
    makeExperiment(50);
    clean();
    

    and this is what happened:

    The garbage collector seems to be doing its job, and you are deleting them correctly for this purpose. However, You are probably using THREE.js Renderer aswell, and if I understand it correctly, the Renderer keeps references to materials, geometries and textures. So if these are not disposed of correctly, they will not be garbage collected. THREE.js has a method for Geometrys, Materials and Textures called .dispose() which will notify the Renderer to remove it aswell. So this is how I would change your clean() function:

    removable_items.forEach(function(v,i) {
      v.material.dispose();
      v.geometry.dispose();
      box.remove(v);
    });
    
    0 讨论(0)
提交回复
热议问题