user18377858
user18377858

Reputation:

How to remove/delete a game object

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(); 

Upvotes: 1

Views: 310

Answers (2)

Brother58697
Brother58697

Reputation: 3178

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

Upvotes: 0

m.marian
m.marian

Reputation: 164

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

Upvotes: 1

Related Questions