QLNEO Posted April 24, 2017 Share Posted April 24, 2017 (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 More sharing options...
samme Posted April 24, 2017 Share Posted April 24, 2017 People usually save a property on the current state (via this): this.text = game.add.text(/*…*/); Link to comment Share on other sites More sharing options...
scheffgames Posted April 24, 2017 Share Posted April 24, 2017 Global variables are not that evil - they do have a purpose and are quite useful if not used badly or in excess and limited to only your app space - ex: MyApp.GLOBALS.myGlob = 0; I do tend to use them a lot for groups in phaser. Link to comment Share on other sites More sharing options...
QLNEO Posted April 24, 2017 Author Share Posted April 24, 2017 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 More sharing options...
Recommended Posts