Loading dynamically named scene

I’m using typescript and have the following:

this.scene.add('ScreenTitle', {key: 'ScreenTitle'}, true, { x:0, y:0 });

Unfortunately this way doesn’t seem to work. If for the second parameter I put ScreenTitle as an object like this then it’ll work:

this.scene.add('ScreenTitle', ScreenTitle, true, { x:0, y:0 });

According to the docs (https://photonstorm.github.io/phaser3-docs/Phaser.Scenes.ScenePlugin.html#add__anchor) I should be able to use a config object for the second parameter but this doesn’t work. Am I doing that wrong? I’d like to add scenes dynamically with a new lines of code.

Based on the typeDefs, you can pass a function, Phaser.Scene or Phaser.Scenes.Settings.Config as the second parameter. Although I do not have any idea how it would work by passing only the config.

The code below will import, add and start the mainScene dynamically.

import MainScene from './mainScene'

export default class PreloadScene extends Phaser.Scene {
  constructor() {
    super({ key: 'PreloadScene' })
  }

  create() {
    this.scene.add('MainScene', MainScene, true)
  }
}

To make it 100% dynamic, you can even use the dynamic import() statement. See code splitting with webpack.

create() {
  let someCondition = true

  if (someCondition)
    import(/* webpackChunkName: "mainScene" */ './mainScene').then(mainScene => {
      this.scene.add('MainScene', mainScene.default, true)
    })
  else console.log('The mainScene class will not even be loaded by the browser')
}

Edit:
I have just added support for it in both of my templates.

Sweet! That worked. Thank you!

1 Like
{key: 'ScreenTitle'}

The scene config object needs at least one of the essential methods (init, preload, create, update), otherwise I don’t think it can do much.