ThreeJS: Remove object from scene

前端 未结 8 1967
后悔当初
后悔当初 2021-01-30 06:45

I\'m using ThreeJS to develop a web application that displays a list of entities, each with corresponding \"View\" and \"Hide\" button; e.g. entityName View Hide

相关标签:
8条回答
  • 2021-01-30 07:21

    I had The same problem like you have. I try this code and it works just fine: When you create your object put this object.is_ob = true

    function loadOBJFile(objFile){            
        /* material of OBJ model */                                          
        var OBJMaterial = new THREE.MeshPhongMaterial({color: 0x8888ff});
        var loader = new THREE.OBJLoader();
        loader.load(objFile, function (object){
            object.traverse (function (child){
                if (child instanceof THREE.Mesh) {
                    child.material = OBJMaterial;
                }
            });
            object.position.y = 0.1;
          // add this code
            object.is_ob = true;
    
            scene.add(object);
        });     
    }
    
    function addEntity(object) {
        loadOBJFile(object.name);
    }
    

    And then then you delete your object try this code:

    function removeEntity(object){
        var obj, i;
                for ( i = scene.children.length - 1; i >= 0 ; i -- ) {
                    obj = scene.children[ i ];
                    if ( obj.is_ob) {
                        scene.remove(obj);
    
                    }
                }
    }
    

    Try that and tell me if that works, it seems that three js doesn't recognize the object after added to the scene. But with this trick it works.

    0 讨论(0)
  • 2021-01-30 07:22

    I started to save this as a function, and call it as needed for whatever reactions require it:

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

    Now you can call the Remove(); function where appropriate.

    0 讨论(0)
提交回复
热议问题