Home > database >  How to remove/delete a game object
How to remove/delete a game object

Time:07-24

How do you make an object that can kill/remove itself? e.g.

var bullet = [];
function bullet() {
  this.removeSelf = () => {
    this = false;
  }
}
function setup() {
  bullet[0] = new Bullet();
  bullet[0].removeSelf();
}
setup(); 

CodePudding user response:

Not sure if I understood your question correctly but if you mean to destroy the object and free the memory then you first need to remove all references to it and then garbage collector will automatically do the job for you.

You're storing a reference to the object in the array so you can do this: bullet[0] = null

CodePudding user response:

If the goal is to remove it from the parent array, you need to edit that array. So we can pass the parent into the instance and have the removeSelf look for its instance in the parent and splice it out.

I also renamed the constructor to Bullet.

var bullets = [];

function Bullet(parent) {
  this.removeSelf = () => {
    const index = parent.indexOf(this);
    parent.splice(index, 1);
  }
}

function setup() {
  bullets[0] = new Bullet(bullets);
  bullets[1] = new Bullet(bullets); // Add a second isntance to the array
  bullets[0].removeSelf();
}

setup(); 
console.log(bullets.length) // Should be 1

  • Related