I’m looking for a way to do data serialization for WebGL, for saving simple data between sessions, without having to put an online webserver just for that.
I ended up in the following page after a short lookup:
He starts talking about PlayerPrefs (with which I do know how to use) and then speaks about other serialization methods, here:
I sandboxed projects for C# serialization and PlayerPrefs tests, but none of them work when deployed (even though PlayerPrefs do work on the editor). I couldn’t find the documentation on the Unity persistence.
Is there any way to save data between play sessions with Unity WebGL? Or an external service (e.g. a NodeJS restful webserver) is the only way to achieve this?
Can I, for instance, access the 5mb web storage from unity somehow?
I put together a simple way to do it and wrote about it here, I include complete source code with error handling. Basically you just create a class to store your game information and mark it as serializable, then create a data access class with your serialize and deserialize methods. Like mentioned elsewhere, for WebGL you’ll need to call SyncFiles, but you can easily do so within your project, as opposed to tightly coupling your project to the webpage it happens to be hosted on.
@dejaime
I do have an online Webserver, which works pretty well in WebGL, but I had a further requirement to keep persistent data to the browser. I just got it working on a test text file, and seems to work well enough for what I need.
For starters I used Application.persistentDataPath, with standard system.io calls. So:-
This basically updates a number in a file, every time the application loads up. This pretty much works as is, except now and again the persistent data doesn’t always update.
I found a post about this (Forum post), and basically you have to use a JavaScript function to ensure the data is persistent.
I don’t know much about JavaScript and how it all fits in, but for now all I do is amend the index.html (create your own WebGL template instead of using the default ones) file generated by the WebGL compilation in Unity, and shove this function in (I put it just before the last 2 lines of the file):-
<script type = "text/javascript" language = "javascript" >
function SyncFiles()
{
FS.syncfs(false,function (err) {
// handle callback
});
}
</script>
To make sure JavaScript was being called correctly, then I used the line alert(“Syncing”); just before the FS.syncfs line. Should popup an alert in the browser.
There is probably a better way, but for now (and I really just finished the code 10 minutes ago) this will do for me, and I thought I’d write it here as I thought a specific answer would be good.
public void setSynthHealth() {
PlayerPrefs.setFloat("synthHealth", (PlayerPrefs.getFloat("synthHealth", 100) - damage));
PlayerPrefs.setString("isThisFallout", "YES!!!");
}
/*
This is totally what Fallout 4 uses for the synth health.
*/