Temporarily remove Sprite from scene?

Hi there,

I was looking at the official Phaser 3 docs and I saw:

 sprite.destroy();

which I have used on multiple occasions, but I have finally hit the point in which I need the sprite properties to stick around. The notes under the aforementioned said:

if you just want to temporarily disable an object then look at using the
Game Object Pool instead of destroying it, as destroyed objects cannot be resurrected

I tried to find anything on “Game Object Pool” and came up empty handed… What would be the best way to go about temporarily removing a GameObject while still keeping it’s properties?

Thanks!

1 Like

Perhaps you might consider just make the sprite invisible?

I thought about this, but I also have actions when the sprite is clicked… so no cigar on that one because someone could accidentally click it while it’s invisible. Another thing I was thinking was potentially moving it out of the scene entirely by changing the x and y to both be like… a billion pixels or something like that, but I figure there’s got to be a better way, ya know?

When you say you need to have the properties stick around, how many properties are they? If it’s not too many, I would consider saving the properties upon destroying the sprite.

this.dormant.push({
x: spr.x,
y: spr.y,
// …
});

spr.destroy();

So basically what you do is you separate the data from the “display”, which is just the sprite. While you destroy the sprite image on the screen, you’ll keep all the entity data. You could even consider creating a class just for this called Entity for example.

class Entity
{
constructor (ctx, x, y, key)
{
this.ctx =_this; // The context, meaning the scene where you init the class
this.x = x;
this.y = y;
this.key = key;
}

 createSprite ()
 {
	if (this.spr) this.spr.destroy();
	this.spr = this.ctx.add.sprite(this.x, this.y, this.key);
}

destroy ()
{
	this.spr.destroy();
}

}

2 Likes

I think this is probably the best way to go about it. Thanks!

Sorry I don’t know how to make all the code go into a code block in this new forum. Still getting used to it!

No worries! Same here

1 Like
sprite.setActive(false).setVisible(false);

or

group.killAndHide(sprite);

See game objects/group/sprite pool.

3 Likes

Thanks again, Samme!