After I destroy a sprite, I’m still able to console.log(this)
it. From what I’ve read, apparently if you want to destroy a game object you have to update all references to the game object to null, so I’m not sure if logging it counts as holding onto a reference to the destroyed object, but I would’ve guessed that trying to log it, would print undefined
or nothing at all seeing as it’s been destroyed. So if someone can please advise me on this, I’d greatly appreciate it.
Here’s my relevant code, to provide context.
export default class GameScene extends Phaser.Scene {
constructor () { super('Game') }
create() {
this.timer = this.time.addEvent({
delay: 1500,
loop: true,
callback: () => {
new Note(this, 60, 150);
},
});
}
}
export default class Note extends Phaser.GameObjects.Sprite {
constructor(scene, x, y) {
super(scene, x, y, 'sharp-a');
this.scene = scene;
this.scene.add.existing(this);
this.scene.events.on('update', (time, delta) => { this.update(time, delta)} );
this.name = 'sharp-a';
this.debugText = this.scene.add.text(x, y + 30, '', { fontSize: 12 });
}
update(time, delta) {
this.x += 2;
// I wraped this in a if-statement because without it, "this.debugText.text = `x: ${this.x}`;" would throw an error
if(this.debugText.scene) {
this.debugText.text = `x: ${this.x}`;
this.debugText.x = this.x + 2 - (this.debugText.width / 2);
}
if(this.x >= 500) {
console.log('destroying', this.name, this.x);
this.debugText.destroy(true);
this.destroy(true);
}
}
}
So as you can see, in the Note’s update
function, I start by console.log()
ing this.name
and this.x
and then to proceed to destroy this.debugText
and this
. The first time this if-statement
is entered, I do expect it to log this.name
and this.x
, because the object hasn’t been destroyed yet, but then it immediately gets destroyed, after which it doesn’t make sense to me that those details should still get logged. If anyone has any insights into what’s happening here, and if I should add/change anything to “properly” destroy the game object, or if this is normal/expected behaviour and I can carry on as-is without any negative consequences, please let me know.