Monday, July 12, 2010

How to save local data with SharedObject using AS3

Sometimes it is needed to save a piece of data on user's computer, for example to load application settings from the last visit, or to load a saved game. This can be easily done with SharedObject.

SharedObject saves data on user's hard drive (up to 100kb by default, if the data size is more than 100kb, a window pops up for the user asking him to allow to store more data). Take a look at this example, enter your name, hit Save and reload the page.



Here goes the code:
// open a local shared object called "myStuff", if there is no such object - create a new one
var savedstuff:SharedObject = SharedObject.getLocal("myStuff");
// manage buttons
btnSave.addEventListener(MouseEvent.CLICK, SaveData);
btnLoad.addEventListener(MouseEvent.CLICK, LoadData);

function SaveData(MouseEvent){
 savedstuff.data.username = nameField.text // changes var username in sharedobject
 savedstuff.flush(); // saves data on hard drive
 }
function LoadData(MouseEvent){
 if(savedstuff.size>0){ // checks if there is something saved
 nameField.text = savedstuff.data.username} // change field text to username variable
 }

// if something was saved before, show it on start
if(savedstuff.size>0){
nameField.text = savedstuff.data.username}

Keep in mind that if there are same Flash files with the same SharedObject functions on different domains, they won't load each other's data. For example, if you play the same Flash game on different websites, it will only load the data that was saved on that exact domain for each Flash.

6 comments:

Rovy said...

I want to know how to save and load a game in SharedObjects in AS3, like in RPG games.

I only learned to save and load score, im just a noob but I want my flash RPG game to be complete, and the Save and Load function is the only one left

Thanks for any help

Kirill Poletaev said...

You can save/load any variables this way. Just set and read properties of the "data" object when you need, you can store as many variables as you want there.

Anonymous said...

Where's the source fle ?

Anonymous said...

chupenme los huevos!

Anonymous said...

wow... I used this to store lots of arrays in my game and it's actually working. Genius script! Thanks very much

Anonymous said...

nbnb

Post a Comment