Share functions between scenes

Hi,

In a game, I have multiple scenes. However, a certain functionality is used in every scene. For example a button to pause the game is present in every scene. So now I have the code to generate this button, and the callback when the button is pressed, available in every scene:

export default class SceneA extends Phaser.Scene {
    //..//
    displayButton(){
        this.add.image(....);
        // and some other code to handle clicks etc
    }
}

export default class SceneB extends Phaser.Scene {
    //..//
    displayButton(){
        this.add.image(....);
        // and some other code to handle clicks etc
    }
}

Is there some way to have this displayButton functionality in every scene, without having to include the method in every scene class?

Thanks in advance!

Hi @Eelco_Luurtsema, I don’t know about such a feature in Phaser, but you can do that your self. Its easy, your code is almost there.

  1. Create a class, say BaseScene from Phaser.Scene with the displayButton method.

  2. Then when you create classes SceneA and SceneB, extend them from the BaseScene class created before.

     export default class BaseScene extends Phaser.Scene {
         //..//
         displayButton(){
             this.add.image(....);
             // and some other code to handle clicks etc
         }
     }
    
     export default class SceneA extends BaseScene {
         //..//
     }
    
     export default class SceneB extends BaseScene {
         //..//
     }
    

Hope this helps.

1 Like

Thanks for your quick reply. Yeah, I was thinking about something like this too, or maybe something like this: https://calebporzio.com/equivalent-of-php-class-traits-in-javascript

Good to know that Phaser does not have something build in for this, so I will follow your example. Thanks!

@Eelco_Luurtsema another thing you can do is, you can have more than one scene running at a time in Phaser. So you can have a game scene and also a HUD scene running at the same time. You can have your HUD scene running on top of the other scenes, where you can place your pause button.
See which approach goes well with your project.

I was unaware you can run multiple scenes. Thanks for the tip, wil look into this!

1 Like

Another way, you can create a new js file and just export a variable or function:

export const displayButton = (scene) => {
  scene.add.image(....); // and some other code to handle clicks etc };
}

and to use it, just import at the beginning of each scene

import { displayButton } from '../script/displayButton.js';
export default class SceneA extends Phaser.Scene {
    //..//
    displayButton(this); // just pass the scene as parameter
}
3 Likes