Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

66
Views
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(); 
5 months ago · Santiago Trujillo
2 answers
Answer question

0

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

5 months ago · Santiago Trujillo Report

0

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

5 months ago · Santiago Trujillo Report
Answer question
Find remote jobs