Reuse code across scenes

Hi, can I display objects in multiple scenes by calling a function defined in one scene, here is the example:

class Scene1 extends Phaser.Scene {
    constructor() {
        super({
            key: ‘scene1’
        })
    }

    create() {
        // I create many objects in this scene
        this.displayObjects();
    }

    displayObjects() {
       this.object1 = this.add.sprite(100, 100,  "key");
       this.object2 = this.add.sprite(100, 100,  "key");
       ...
    }
}

Now, I would like to display same objects in Scene 2 by calling displayObjects method from Scene1. How can I reuse code when working with scenes?

class Scene2 extends Phaser.Scene {
constructor() {
super({
key: ‘scene2’
})
}

    create() {
        // display objects from Scene 1
    }
}

You could create your own basic scene in a separate file

class BaseScene extends Phaser.Scene {
    constructor() {
        super({
            key: null
        })
    }

    create() {
        // I create many objects in this scene
        this.displayObjects();
    }

    displayObjects() {
       this.object1 = this.add.sprite(100, 100,  "key");
       this.object2 = this.add.sprite(100, 100,  "key");
       ...
    }
} 

then use your new base class like

class Scene1 extends BaseScene {
    constructor() {
        super({
            key: ‘scene1’
        })
    }
    // You do not need to rewrite methods that exist in baseScene
   // You can override them by creating
   // methods of the same name 
}

make sure to import the BaseScene file in every scene that extends from it.
Theorically it’s like this. Haven’t tested it yet.Let me know if there’s anything unclear/wrong :slight_smile:

Alternatively, instead of using inheritance, you can create a common function that accepts a Scene object argument, and in that function it create your objects on the supplied scene.

1 Like