Jump to content

Avoid global variables while working with states?


QLNEO
 Share

Recommended Posts

(For context, I'm very new both to this forum and with Phaser!)

So, while working with state methods like preload, create and update, you will frequently need to work with variables created in one method to the other, right? For example:

create: function() {
    text = game.add.text(0,0,"Hello World",{fill: "white"});
},

update: function() {
    text.setStyle({fill: `rgb(${red},0,0)`});
    red += 5;
}

// red is a global variable declared outside the state

Both red and text are globals, so they can be shared between create and update

How do I avoid using globals altogether? I do believe using IIFEs is a solution, but it doesn't seem the best one. For example, is the text object created in Game.add.text() stored somewhere by Phaser so it could be retrieved in the update method without it having to be assigned to a variable like text?

Link to comment
Share on other sites

4 hours ago, samme said:

People usually save a property on the current state (via this):


this.text = game.add.text(/*…*/);

 

Gee, that worked better than I expected! Thanks!
I wonder, how does it know this refers to the state and not the create or update function?

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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