Jump to content

'game' properties are null when accessed from the script, but not in the console


wombat
 Share

Recommended Posts

This baffles me. 

 

If I do this

game = new Phaser.Game(800, 400, Phaser.AUTO, '');console.log(game)console.log(game.add)

the output in the browser console is this:

>Phaser.Game

null

 

However, if I type "game.add" in the console the output is what I expected (ie >Phaser.GameObjectFactory).

 

I ran into this because I wanted to create some shorthands in the start of the script for accessing common functions and making it more comprehensible (to me), like so: var factory = game.add;

 

Please, what's going on?

Link to comment
Share on other sites

Thank you. Does that mean that the 'game' instance is not fully initialized when it's created (and returned), but is instead initializing itself at some (not very distant, since waiting for 0 ms is enough to let it complete) later time?

 

Is that a javascript thing or a Phaser thing? 

Link to comment
Share on other sites

null interval sets the execution to "as soon as possible" time. so when all pending operations (including full initialization of the game instance) are complete, interval fires. it is js specific. and remember this trick. it is also very usable in web-page programming)

Link to comment
Share on other sites

  • 2 weeks later...

That's interesting. How do I know when I have to worry about objects not being initialized? Can I be sure that if the objects have time enough to initialize on my computer, the code will work on any computer? Or should I always put a setTimeOut statement after I create the game object? Should I do some kind of testing to find out if there are other places in the code where this could happen? 

Link to comment
Share on other sites

Usually events or callbacks are fired to let you know when something is ready. JavaScript is typically employed in highly asynchronous environments and asynchronous programming is something that can be quite tricky to start with. In the case of Phaser, you would usually do your setup and initialisation within the preload and create states, which would ensure the game object is ready to be used. The code above should work on any computer, as it's not a case of waiting for a specified time, but ensuring that your code gets put to the end of the 'queue' of things JavaScript is currently doing. The setTimeout trick above does just that.

 

See this for more information: http://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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