Accessing the game or scene instance outside of the create & update function

I am a beginner in Phaser 3. I create a game instance as follows:

game = new Phaser.Game({
    type: Phaser.AUTO,
    width: 800,
    height: 600,
    scene: {
        preload: preload,
        create: create,
        update: update
    },
    physics: {
      default: 'arcade',
      arcade: {
        debug: true,
        gravity: { y: 0 }
      }
    }
});

game is a global variable. What i want to do is access the instance referenced by “this” in the create & update functions outside of these functions. I tried to use the global game instance but it doesn’t work.
What does “this” reference in this case ? and How can I access this instance outside of the create & update function ?
Thanks!

What is the purpose of accessing game variable? In most cases, you can do whatever you want without accessing game variable.

this variable inside create/preload/update function refers to the scene those function belong to.

How can I access the scene instance outside of the create/preload/update in that case ? I’ve tried game.scene but it seems that it’s not it…

if you’re following same structure as examples here. Then this variable refers to the one and only scene that is added in the game. In above code you shared, there is only one scene in game.

You can obtain it from game.scene (which is the Scene Manager) but you may find it simplest to do:

defaultScene = null;
game = new Phaser.Game(/* … */);

function preload () {
  defaultScene = this;
  // …
}
1 Like

While this is probably the same if not similar to accessing it through the scene manager as samme says, another thing you can do with less code is pass your instances as properties to a global object literal as such:

const gameState = {};

// Game(config) stuff…

function preload()
{
// preloaded stuff
}
function create()
{
gameState.instance = this.add.image(338, 600, ‘left’);
}
function upload()
{
gameState.instance.doStuff // now instance is available globally but not floating in space
}