How I can save game progress to json

I need to save json file with my game progress and I don’t know how I can do this. I found couple links with posts about saving on IOS but JS engine doesn’t have this methods. Thanks for help.

sys.localStorage.setItem(“save”,JSON.stringify(object));
to save data

var memory = sys.localStorage.getItem(“save”);
to load data

it works in v2.2, not sure it still works in v3.x

2 Likes

Thanks for fast answer. I use version 3.

I do it this way.

I have a class GameState.js witch hold loaded json object with game state in memory and have functions load() to load state when game starts and save() to save state whenever we need to.

    var GameState = cc.Class.extend({
    
    	data: null,
    	loadCallback: null,
    
    	load: function(loadCallback) {
    		this.loadCallback = loadCallback;
        
    		var self = this;
    		cc.loader.loadJson(res.GameState_json, function(error, data){
    			self.data = data;
    			self.loadCallback();
    		});
    	},
    
    	save: function(){
    		cc.sys.localStorage.removeItem("GameState");
    		cc.sys.localStorage.setItem("GameState", JSON.stringify(this.data));
    	}
     });

var gameState = new GameState();

loadCallback is used to load game state before we start to load game itself. Something like this:
(it is onEnter function in preloader scene)

   onEnter: function () {
      cc.Node.prototype.onEnter.call(this);

      var self = this;
      gameData.load(function(){ //load game data
        cc.log("data loaded");

        gameState.load(function(){ //load game state
            cc.log("state loaded");

            self.init(); //create grafical part of preloader
            self.schedule(self.startLoading, 0.3); //start loading resources
          }
        });
      });
    },

GameData class is the same as GameState the only difference it that GameData loads game data(stings, urls, achievements description and etc) and do not have save() function …no need to :smile:

3 Likes

Thank you guys. Your answers very helped me.

I want to safe these Jsons in file system, but I’m not sure how to use the given jsb.fileUtils methods to achieve this goal.
Do you have any hints?

See this topic.