P4UL Posted August 6, 2016 Share Posted August 6, 2016 Hello! I have a game with multiple states. The logic in all states is the same. The only thing that changes is the tilemap used in the create function. All other objects are the same in all states. I could simple duplicate one file with the state for every tilemap. Is there an easier way to do this? I would really like to re-use one state for all tilemaps. As far as I understand how states work the create function will be called every time the state is started. So I believe there must be a way to give the name of the tilemap as a parameter to the create function or something similar. Thanks in advance! Link to comment Share on other sites More sharing options...
mcolman Posted August 7, 2016 Share Posted August 7, 2016 You could use class inheritance. So call your main game state MainState, and then each other state would extend MainState. Something like: State 1 extends MainState { create() { // add your custom tilemap here super.create() } } This syntax is using es6 fyi. Hope this helps. P4UL 1 Link to comment Share on other sites More sharing options...
P4UL Posted August 7, 2016 Author Share Posted August 7, 2016 I had not thought about class inheritance. In the meantime I tried to store the name of the next tilemap in a global variable and reading this variable in the create function. It worked but your idea is much better and cleaner. I will rewrite my code to use class inheritance for the states, thank you very much! Link to comment Share on other sites More sharing options...
Tom Atom Posted August 7, 2016 Share Posted August 7, 2016 Hi, when you call game.state.start, you can add multiple optional parameters: game.state.start("Mystate", true, false, param1, param2); These parameters are then passed to init() method, if you have any in your state (init is called as first before create()). With this, you can pass variables from state to state. You can still combine it with inheritance solution and have cleaner code. P4UL 1 Link to comment Share on other sites More sharing options...
P4UL Posted August 7, 2016 Author Share Posted August 7, 2016 I didn't knew this is possible, thank you very much! Link to comment Share on other sites More sharing options...
symof Posted August 8, 2016 Share Posted August 8, 2016 You can also use game.state.states['MyState'].myGlobalVariable = "Value"; And this can be called from all other states. This is what i use to carry a variable between states. I find this to be much easier then the other examples, however the downside is that you get really big variable names. P4UL 1 Link to comment Share on other sites More sharing options...
Recommended Posts