ThreeJS: Remove object from scene

前端 未结 8 1972
后悔当初
后悔当初 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.

提交回复
热议问题