Any tips for making a cross-scene manager / singleton?

New to Phaser 3 in general, and coming from briefly using Unity. In Unity, a common pattern is to use a Singleton Game Manager to manage state, and can use “Don’t Destroy on Load” to keep it active among scenes. Any tips to recreate a similar pattern in Phaser?

I have an inventory that needs to be updated globally, but I switch scenes constantly to explore an environment, as each section of the environment is its own scene.

I’ve briefly looked into the data section, it seems I can use this / attach my own objects to this (?). Anyone encounter a similar problem / have a good solution? Thanks.

I just did something like this! I created a PersistencePlugin that’s a global plugin for the game.

You can take a look at it here: https://github.com/snowbillr/archer-adventure/blob/master/src/plugins/persistence-plugin.ts

and see how it’s loaded into the game here: https://github.com/snowbillr/archer-adventure/blob/master/src/index.ts#L24

and see how I use it here https://github.com/snowbillr/archer-adventure/blob/master/src/scenes/hud-scene.ts#L21 and here https://github.com/snowbillr/archer-adventure/blob/master/src/components/adventurer-component.ts#L35

At its core its just a key/value store that’s stored on the game level rather than the scene level.

3 Likes

Woah! This looks like exactly what I need.

New to Typescript, and the concept of “Plugins” so I’m probably gonna study your code / the syntax for a bit haha. I’ll let you know if I have any questions!!

Sounds good, happy to help!

TL;DR on plugins: they are either at the Scene level or the Game level. Scene plugins have an instance given to every scene, Game plugins have a single instance given to the game.

1 Like