Jump to content

Variables, States, and Scope


Andromedus
 Share

Recommended Posts

Hi - first time post here so hello to everyone.  Enjoying Phaser so far!

I've got a basic game framework working using States.  I'm new to Javascript, coming from an AS3 background where I would use separate classes with variables local to each class.  In a similar way, I'm trying to work out how to define a variable which is local to a particular state.  

To put it another way, how/where would I define myVar, such that:

var state1 = {

    create: function(){
        //myVar used here
    },

    update: function(){
        //myVar used here too
    }
}

var state2 = {

    create: function(){
        //myVar not accessible here
    }
}

I realise that I could define myVar outside of both states, but then it would be global to all states.  In my case, myVar is actually an object which has a whole load of properties and display objects, so potentially a lot of stuff to persist across states without getting garbage collected when I change states.

Thanks in advance for any advice.

 

Link to comment
Share on other sites

Hi, you can do this:

var state1 = {

    create: function(){
        //myVar used here
        console.log(this.game.state.states["s2"].greet);
    },

    update: function(){
        //myVar used here too
    }
}

var state2 = {

    greet: "hello",

    create: function(){
        //myVar not accessible here
    }
}

game = new Phaser.Game(1080,600, Phaser.AUTO, 'game');

game.state.add('s1', state1);
game.state.add('s2', state2);
game.state.start('s1');

 In state1 you are accessing varibale from state2.

Link to comment
Share on other sites

Thanks Tom.

So ... you're creating the 'greet' variable as a key/value pair of the state object.  That makes sense, and in that case I guess I could even just access it where I need it with 'state2.greet' (or 'this.greet' if I want to access it from within the same state), like this:

 


var state1 = {

    create: function(){
        
        console.log(state2.greet);
    },

    update: function(){
        
        console.log(state2.greet);
    }
}

var state2 = {

    greet: "hello",

    create: function(){
        console.log(this.greet);
    }
}

game = new Phaser.Game(1080,600, Phaser.AUTO, 'game');

game.state.add('s1', state1);
game.state.add('s2', state2);
game.state.start('s1');

 

Thanks, I'm beginning to get my head around this now.

 

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...