0

Here is my code, I wonder if the delete is good enough to destroy an object and that there is no memory leak :

class Shoot extends MovableObject{
constructor(){
    super();
    this.speed = 2;
    this.geometry = new THREE.CircleGeometry(0.5);
    this.material = new THREE.MeshBasicMaterial({ color: 0xffffff });
    this.mesh = new THREE.Mesh(this.geometry, this.material);
}

setRotation(rotation){
    this.mesh.rotation.set(rotation.x, rotation.y, rotation.z);
}

setPosition(position){
    this.mesh.position.set(position.x, position.y, position.z);
}

}

Later i've got this function, listShoot is the only place I have Shoot instances :

var position;
listShoot.forEach(function(shoot, i, list){
    position = shoot.getMesh().getWorldPosition();
    if(/*i want to destroy my shoot*/){
        list.splice(i, 1);
        scene.remove(shoot.getMesh()); // This is ThreeJS
        delete shoot;
        console.log("shoot destroyed");
    }
});
Valentin Parsy
  • 385
  • 1
  • 2
  • 11
  • there is no memory leak – The Reason Jun 09 '16 at 10:25
  • Although there is an answer here that has been accepted, there are extra things you may want to consider if you are using three.js. Search stack for something like "three.js delete object" – 2pha Jun 09 '16 at 13:53

2 Answers2

0

Although I can't give you a complete answer, I do know that you can't delete variables which are part of a closure.

var myfunc = function(a, b, c) {
  console.log(a,b,c);
  delete b;
  console.log(a,b,c);
}; 

myfunc(1,2,3);

The above code will output the following:

1 2 3
1 2 3

As for garbage collection in closures have a look at this related question.


You can always assign undefined to the variable.

var myfunc = function(a, b, c) {
  console.log(a,b,c);
  b = undefined;
  console.log(a,b,c);
}; 

myfunc(1,2,3);

Which outputs:

1 2 3
1 undefined 3
Community
  • 1
  • 1
evolutionxbox
  • 3,932
  • 6
  • 34
  • 51
0

I think you just should null the shoot variable, to lose the link. Like this:

shoot = null;
console.log("shoot destroyed");
Telman
  • 1,444
  • 1
  • 9
  • 12