How to restart a game gracefully?

Hi,

When I need to replay a game or play another level of the game, the only way I know is to call create() again from somewhere in the scene. By doing this, it creates an extra copy of create() running, and causes problems of course.

What is the proper way to replay a game or a new level of the game? Can anyone please advice me?

<html lang="en"> 
<head> 
    <meta charset="UTF-8" />
    <title>Sum 100</title>
    <script src="//cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>

<script>

function setTime () 
{
    ++totalSeconds;
    console.log(totalSeconds);
}

var totalSeconds = 0;
 
var GameScene = new Phaser.Class({
    Extends: Phaser.Scene,

    initialize:

    function GameScene ()
    {
        Phaser.Scene.call(this, { key: 'GameScene', active: true}); 
    },

    preload: function ()
    {
    },

    update: function ()
    {
        this.timerText.setText('Time: ' + totalSeconds);
            if (totalSeconds % 10 == 5) {
                            this.create();
            }
    }, 

    create: function ()
    {
        this.timerText = this.add.text(32, 32);
        setInterval(setTime, 1000);      
    }
});

var config = {
    type: Phaser.AUTO,
    width: 780,
    height: 540,
    parent: 'phaser-example',
    pixelArt: true,
    backgroundColor: '#F00000',
    scene: [GameScene ]};

var game = new Phaser.Game(config);

</script>
this.scene.restart();

You should avoid setInterval(). Use a looping timer event instead.

1 Like

why is a looping timer event better than using setInterval?

Similarly, I assume Phaser would prefer if I use some built in timer event rather than setTimeout … why?

setTimeout() etc. are not synchronized with the game clock, do not pause when a scene pauses, and need to be removed before stopping/restarting a scene.

2 Likes