Data Persistence

Saving Games Online in Unity WebGL

Clicking games are, in fact, barely games. That considered, a few of us got caught up in Canada Clicker and enjoyed how ridiculous it was. During this vacuous time, I was challenged to make a trite clicker of my own (Night of the Clicking Dead). I thought it would be a good opportunity to try some things that I haven't before. As it turns out, I decided to make this my first WebGL project that would allow the user to save their game state. After all, it wouldn't be a clicker if you couldn't gain advancements that automatically accrued between sessions. I'm going to discuss the save process I implemented as well as my leveraging of JavaScript alerts used in error handling. Done so entirely within Unity, opposed to having to add the script to the webpage directly.

Serializable Game Details

I created a standard class to house all of the player's session details. This class is instantiated and used in my Unity game manager class to keep track of everything.

The first key point here is the use of Application.persistentDataPath. Unity already went through the trouble of making this platform safe. This is where our save file will be physically stored.

The second area of note is that when saving in WebGL, we need to call SyncFiles(). This lets us leverage IDBFS, which provides a POSIX-like file system interface for browser-based JavaScript.

Non-Compiling Unity JavaScript

In order for PlatformSafeMessage() to work and to be able to call SyncFiles(), we have to interact with browser JavaScript. The standard way to do this is to use the Application.ExternalCall() and Application.ExternalEval() functions and to manually embed the script on your webpage. That is gross. Fortunately we can now add our JavaScript sources to the project, and then call those functions directly from script code. To do so, place files with JavaScript code using the .jslib extension (as the normal .js would be picked up by the UnityScript compiler) into a "Plugins/WebGL" folder in your Assets folder. The file needs to have a syntax like this:

That's it. Now you're serializing your save data to the browser. Users can play your online games and come and go without having to start over. A basic but important concept, funny I got to it with a clicker.