Global plugin with its own data manager and event emitter

I have multiple “main” scenes where the actual game happens and only one of them can be active at a time. There’s a few other scenes on top of it with various UI elements. Interactions with those UI elements may result in the scene being changed. So far when switching between main scenes, I was just calling this.scene.start('AnotherMainScene') from within the context of a main scene.

However, this won’t work when I need to change the main scene from one of the UI scenes, so I thought about writing a global plugin for keeping track of which main scene is currently active and also allowing any place in the game to switch the current scene. The plugin would keep track of some state for the save/load game system and also emit events so that other scenes can react to the main scene being changed.

In the DataManager docs there’s this fragment:

The Data Manager Component features a means to store pieces of data specific to a Game Object, System or Plugin. You can then search, query it, and retrieve the data. The parent must either extend EventEmitter, or have a property called events that is an instance of it.

So it seemed like a perfect thing for my use case. However, I couldn’t find any examples of integrating a data manager with a custom plugin. I hacked the following thing, but I’m not sure if this is how a custom plugin is supposed to integrate with a data manager and an event emitter.

Am I doing anything wrong here or is this code just fine?

class MainScenePlugin extends Phaser.Plugins.BasePlugin {
  constructor(pluginManager) {
    super(pluginManager)
  }

  init() {
    this.events = new Phaser.Events.EventEmitter()
    this.data = new Phaser.Data.DataManager(this)
  }
}

There shouldn’t be anything wrong with your current solution. If your plugin will ever get destroyed, you should destroy() the Data Manager, too. If you’re not comfortable making your own Data Manager, the Game instance has a global one, game.registry.

Thanks for the tip! I was actually looking for a global data manager, but couldn’t find it because I assumed it’s somewhere under the data property. :man_facepalming: