Remove custom class object from the scene (ES6)

Hello,

I am new to Phaser 3 and I have a question about removing objects from the scene. I have created a custom button class Button.js which I import and call when I need a button in the scene and everything works just fine but the problem arises when I need to remove a button from the scene.

Here is the Button.js class:

class Button {
    constructor(x, y, label, scene, callback) {
        const button = scene.add.text(x, y, label)
            .setOrigin(0.5)
            .setPadding(10)
            .setStyle({ backgroundColor: '#111' })
            .setInteractive({ useHandCursor: true })
            .on('pointerdown', () => callback())
            .on('pointerover', () => button.setStyle({ fill: '#f39c12' }))
            .on('pointerout', () => button.setStyle({ fill: '#FFF' }));
    }
}

export default Button;

Now I call it inside of a scene like this:

        let closeButton = new Button(460, 25, "X", this, () => {
    
            console.clear();
            console.log("Exiting game!");
            
            camera.fadeOut(1000, 0, 0, 0);
            camera.once(Phaser.Cameras.Scene2D.Events.FADE_OUT_COMPLETE, (cam, effect) => {
                this.time.delayedCall(1000, () => { // Make pause between scenes / transitions
                    this.scene.start("Game");
                })
            })
        });

Is there a way of removing this button from the scene when no longer needed (not in this particular case)? Do I need to extend some Phaser 3 classes in my custom class or is there some other solution? I would greatly appreciate it if you could point me in the right direction.

Thanks!

You can permanently remove a game object by its destroy() method.

You’ll need to save the game object so you can reach it later.

// class Button
this.button = scene.add.text(x, y, label) // …

// Scene
closeButton.button.destroy();

Thanks samme for the help with this… There was a little bit pushing and pulling but in the end I managed to solve this as follows:

// class Button
class Button {
    constructor(x, y, label, scene, callback) {
        
        let button = scene.add.text(x, y, label)
            .setOrigin(0.5)
            .setPadding(10)
            .setStyle({ backgroundColor: '#111' })
            .setInteractive({ useHandCursor: true })
            .on('pointerdown', () => callback())
            .on('pointerover', () => button.setStyle({ fill: '#f39c12' }))
            .on('pointerout', () => button.setStyle({ fill: '#FFF' }));

            this.button = button; // <-- THIS LINE ADDED
    }
}

export default Button;

… and in the Scene as you suggested:

// Scene
closeButton.button.destroy();

Now it works just great and as intended. Thanks for the help. :slight_smile:

1 Like