'Phaser 3 Switching Scene Overlapping Text

I'm creating a user interface. I am passing text between the main scene and the subscene.

What I intend to do is reuse a subscene and change the text depending on which button is pressed. On "button 1" pressed, go to subscene and show "button ONE pressed". Then go back to main scene when text is clicked. On "button 2" pressed, go to subscene and show "button TWO pressed". Then go back to main scene when text is clicked.

However the text overlaps after both buttons have been pressed.

enter image description here

I thought it would create a new scene but it looks like it is adding new text to the same scene instead. How can I solve this?

scenes.js

class MainScene extends Phaser.Scene 
{
    constructor ( )
    {
        super();

        Phaser.Scene.call(this, { key: 'mainscene' });
    }

    create()
    {
        const button1 = this.add.text(100, 100, 'button1', { fill: '#0f0' });

        button1.setInteractive();

        button1.on('pointerdown', this.button1Pressed, this); 

        const button2 = this.add.text(100, 200, 'button2', { fill: '#0f0' });

        button2.setInteractive();

        button2.on('pointerdown', this.button2Pressed, this); 
    }

    button1Pressed () 
    {
        this.scene.start('subscene', { text_to_print: "button ONE pressed"});
    }

    button2Pressed () 
    {
        this.scene.start('subscene', { text_to_print: "button TWO pressed" });
    }
}

class SubScene extends Phaser.Scene 
{
    constructor ( )
    {
        super();

        Phaser.Scene.call(this, { key: 'subscene' });

        this.text_to_print = null;
    }

    init ( data )
    {
        this.text_to_print = data.text_to_print;
    }

    create()
    {
        
        
        var style = { font: "65px Arial", fill: "#777777", align: "center" };
        var text = this.add.text(100, 100, this.text_to_print, style);

        text.setInteractive();

        text.on('pointerdown',this.goBack,this);
    }

    goBack()
    {
        this.scene.switch('mainscene');
    }
}


var config = {
    type: Phaser.AUTO,
    scale: {
        mode: Phaser.Scale.FIT,
        autoCenter: Phaser.Scale.CENTER_BOTH,
        width: 960,
        height: 540
    },
    scene: [MainScene, SubScene ]
};

var game = new Phaser.Game(config);

scenes.html

<!DOCTYPE html>
<html>
<body>

    <script src="phaser.min.js"></script>
    <script src="scenes.js"></script>
    
</body>

</html>



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source