Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a variable to Android using Cocos2D-JS?

I am trying to save a high score integer to the user's Android system, so that it can persist throughout all game-play experience.

I have read that using Cocos2D-X one can use NSUserDefaults but this doesn't seem to be available in the Cocos2D-JS API at all.

Anyone has any experience with this, is there any other efficient way how to tackle this issue?

like image 303
magicode118 Avatar asked Dec 05 '22 05:12

magicode118


1 Answers

When using Cocos2D-JS for compiling native apps, you can simply use localStorage just like if you were running your game in the browser :D

For example:

//Handle for quick access to Cocos2D's implementation of Local Storage:
var ls = cc.sys.localStorage;

var value = "foo";
var key  = "bar";

//This should save value "foo" on key "bar" on Local Storage
ls.setItem(key, value);

//This should read the content associated with key "bar" from Local Storage:
var data = ls.getItem(key);

cc.log(data); //Should output "foo" to the console.

//This should remove the contents of key "bar" from Local Storage:
ls.removeItem(key);

//This should print "null"
data = ls.getItem(key);
cc.log(data);
like image 138
Sebastián Vansteenkiste Avatar answered Dec 09 '22 13:12

Sebastián Vansteenkiste