8Bit's Save Data Handler

alright, so i’ve seen some people ask for help with saving data, and i decided to make a system (aka class) for those people!
SaveDataExample.wick (54.7 KB)

behind the scenes

a line-by-line explanation of the code:

var data = JSON.parse(localStorage.getItem(key))

based on some tests i’ve done, localStorage can’t store JSON data.
to work around this, we stringify it first before storing.
if you want to look at another example, of this parsing/stringifying system, you can check the mozilla dev docs for JSON.parse().

if(data === null || data === undefined || data == 'undefined'){ 
    data = template
}

if the save data is being initialized for the first time, the data that is supposed to be in localStorage doesn’t exist yet.
this prevents an error by resetting the data to the template that is defined in the constructor. the template should resemble this:

{"score":0,"amogus":"sus"}

it should contain everything that is set/called/saved in your project.

the reason for so many if checks is because the save data can be many different values, a few of which we don’t want.

this.data = data

literally just so we can access data later. that’s it.

flush(){
        localStorage.setItem(this.key,JSON.stringify(this.data))
}

much like in haxeflixel’s save library, you need to run flush() whenever you change data.
stringifies the data so it can be saved
run on initalization

for a few people

attentive viewers may notice that the system showcased here is basically the same as the system i made for D-RSRG: 8Bit Engine. and you’d be correct. i just decided to release it separately so that the system wasn’t tied to the engine specifically

filler text

2 Likes

Thank you for this tutorial! Very helpful.