Sign in to follow this  
joshcawthorne

Carry score over through resets and new levels?

Recommended Posts

Hi all,

I have code for a crystal count within my level at the moment, however when the player dies and the level resets, or when the player moves on to level 2 (in a new js file), the score resets as I've initiated it within level 1.

Could someone please tell me how to create a variable that can be tracked and edited in every JS file, rather than just one?

Thanks!

Share this post


Link to post
Share on other sites

You must create a global variable. That is, declare a variable score right in the beginning of a file for example so it has global scope and can be acessed in all the files.

example: var score = 0;

then just do whatever you want to score like score+= 1; Its value will be the same in other js files

Share this post


Link to post
Share on other sites

Globalising variables is the only way to share state between different script includes, `var score` gets translated to `window.score` in the browser and window is available to all of your scripts but JS has shorthands for accessing window properties (its probably best to refer to these as root scope, but in the browser this is the window object).

The alternative is to wrap your code up using a module system, such as browserify or webpack (for example) but this is a far more involved way to solve your issue of sharing state across files and you might want to crack on and finish up this project first before looking to see how a module system can help you to write better code. On a side note Safari have just shipped a module implementation to a dev channel so real strides are being made to sort this out in the browser!

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Recently Browsing   0 members

    No registered users viewing this page.