You are on page 1of 9

As3 tutorial

Saving and Loading in Actionscript


3 (Mini-Lesson)
Feb

28by Ben Reynolds

One thing you want to do as a game developer is make your players want to
come back to your game more than once. And one of the best ways to
accomplish this is to enable them to save their data for persistent gameplay.
You might expect saving and loading to be tough to implement, but
actionscript 3 is helpful enough to include the powerfulSharedObject, which
makes saving and loading data a piece of cake.
In this tutorial, we will create the following demo. Click the +1 button a few
times to add to your score. If you refresh this webpage without clicking the
save button, your score will revert to 0 when the page loads. But if you do
click the save button, your score will load automatically the next time you
load the page. Try it out!

SharedObject: The force behind saving and loading


A games ability to save and load data (such as the players highscore) requires
a few different lines of code, all of which have to do with
the SharedObject data type. All you need to do is create a SharedObject
variable. Then you can give it simple messages, and it will do the dirty work
of reading and writing to the players local disk for you.
The following steps will implement everything you need to save and load data.
After we go through these basic steps, we can test it out with the demo.

1. Create a SharedObject variable.

Before we can start using the shared object, we need to create it. Declare the
variable the same way you would any other but dont give it a value yet.
var saveDataObject:SharedObject;

2. Tell the SharedObject where to save and load


Right after you create the variable, set it using
the SharedObject.getLocal function. This function will look for a specific
file on the players computer, which will contain your data. If the file doesnt
exist yet, it will create one. The exact string you pass into this function doesnt
really matter it will be used as part of the file name, but most players will
never see it. I usually just set mine to test while Im working on the game,
and then change it to the title of my game when I publish it.
saveDataObject = SharedObject.getLocal("test");

(Note: You can combine this with the previous step and just write var
saveDataObject:SharedObject = SharedObject.getLocal("test"). The only reason I
divided into two sections is for clarity.)

3. Add any variable to the data property of your


SharedObject
Here is the meat of the actionscript which handles saving. The past two steps
set up the shared object. Now we are actually writing data to that object.
The SharedObject data type has a built-in object variable called data.
Now, if youve been following my tutorials you may not have run into the
official object data type so far. Its a very flexible data type, which you can
think of almost as a container for a bunch of other sub-variables, or
properties. For example, if I wanted to create a new object variable I might
write: var myDataObject:Object = {highscore:100, myName:"Player 1",
time:10.4} and then I can access or modify the value of one of these properties,
for example, the highscore, by using myDataObject.highscore

The cool thing is that the data Object is built into a SharedObject, so all you
need to type to save something is:
saveDataObject.data.savedScore = currentScore;

Notice, you dont even need to define the savedScore property of the data
Object before you can set it to a value.

4. Tell the SharedObject to write the data to the local file


Setting a value to the data in the shared object wont actually save anything
immediately. It saves everything when the player quits the application, but
never only rely on that it wont work if the player navigates away from a web
page, the application crashes, etc, etc.
When you want the SharedObject to actually, immediately write its save data
to its file on the players local hard drive you flush it:
saveDataObject.flush();

This is a very processor intensive action to call, so use it sparingly (never


include it an a loop function). The game will probably lag for a half-second or
so whenever you flush the save data, so be careful when to do it (but dont
leave it out entirely, or your players will be unhappy when they discover their
data to be missing).

5. Load anything you have saved in the SharedObjects


data
Loading is literally the opposite of saving. Instead of saving a variables value
to the saveDataObject.data, we just set the value of our variable to its
respective property of the saveDataObject.
To load currentScore from the savedScore, we would write:
currentScore = saveDataObject.data.savedScore;

Testing it out:
Time to go from theory to a practical test. Our test project will include a
variable that keeps track of the players score. Clicking a button will add one
point and update the text field to display the current score. Clicking the save
button will save the current score to a shared object, and flush the data to the
players local drive.

Setting Up
Create a new Flash Professional project. We are going to set up the stage so
that it looks like the following screenshot:

First use the rectangle tool to create two buttons. It doesnt matter too much
what they look like, as long as you label them so you can tell them apart.
Next, I converted them one at a time into Symbols of the Button type (Modify
> Convert to Symbol). Name one of them btnAdd and the other btnSave.

Then, for simplicitys sake, give each button an instance name identical to its
symbol name (btnAdd and btnSave).

Because this is just a test, it doesnt really matter how the buttons look.
However, I did spend a little time adding some effects to the buttons so that
they change color when the player hovers their mouse cursor over the buttons,
or clicks on them. It doesnt require any code at all, so if youre curious to see
exactly what I did, just check out my source file (all you need to do is add more
frames to the Button Symbol, like in the image below).

After your buttons are set up and code-ready, create a text field above them
(using the Text Tool) and type Score: 0 inside it. Make sure to make it
a Dynamic Text Field (by using the drop-down list in the Properties panel).
This will allow you to give it an instance name, and therefore modify it with
code. Give it the instance name txtCode.

Note: In the interest of staying organized, it is considered good practice to


add a prefix to your instance names according to what kind of object they
are. For example, I give my Buttons the btn prefix, and my Text Fields the
txt prefix. Some people even give their Movie Clips the mc prefix but I
usually ignore that one ;-)

Time to Code

OK, open up your Actions panel for frame 1 of your main project timeline.
Start by declaring two variables: the currentScore, which will keep track of
how much score to display in the txtScore field, and the saveDataObject,
which is our Shared Object, and the focus of the tutorial.
1
2

var saveDataObject:SharedObject;
var currentScore:int;

Next, we need to create the init() function, and call it once to initialize the
project. Ive included everything in this function that it will include in the final
version, so dont be startled if you see something in there that we havent even
discussed yet. Ive commented everything, explaining as you read along. Ill
also explain afterwards.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

init(); // this line goes directly beneath the variables


function init():void{ // call once to set everything up

saveDataObject = SharedObject.getLocal("test"); // give the save data a location


currentScore = 0; //start with 0 score
btnAdd.addEventListener(MouseEvent.CLICK, addScore); // clicking on +1
btnSave.addEventListener(MouseEvent.CLICK, saveData); // clicking on Save
if(saveDataObject.data.savedScore == null){ // checks if there is save data
trace("No saved data yet."); // if there isn't any data on the computer...
saveDataObject.data.savedScore = currentScore; // ...set the savedScore to
} else {
trace("Save data found."); // if we did find data...
loadData(); // ...load the data
}

updateScoreText(); // finally, update the text field

The first thing we do in this function is use


the SharedObject.getLocal function to tell the saveDataObject where to
look for and save the data file. Next, we set the currentScore to 0, for the
obvious reason that we are initializing the game with default values. The next
two lines add Event Listeners to the two buttons. The btnAdd button will call

theaddScore function when it is clicked, and the btnSave button will call
the saveDatafunction.
The next little section of code might look a little more complicated, but all it
does is check whether or not there is previous save data on the
computer. How can we figure out whether there is save data or not? Well,
one way is to check if our savedScoreproperty in the shared objects data
is null. If we have saved data previously, that data will have a value other
than null, so the conditional will be false, and well call theloadData function.
But if we never set the savedData to be anything, it will be null, so we wont
load the data. Instead, well just start by setting the score to 0.
Finally, we call a function to update the txtScore field.
Here are the 4 other functions which we reference in the initialization. This is
the entire remainder of the code in our demo program. You can add these
functions anywhere I just put them beneath the init function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

function addScore(e:MouseEvent):void{
currentScore += 1; // add 1 to the score
updateScoreText(); // update the textfield
}

function saveData(e:MouseEvent):void{
saveDataObject.data.savedScore = currentScore; // set the saved score to the cur
trace("Data Saved!");
saveDataObject.flush(); // immediately save to the local drive
trace(saveDataObject.size); // this will show the size of the save file, in byte
}

function loadData():void{
currentScore = saveDataObject.data.savedScore; // set the current score to the s
trace("Data Loaded!");
}

function updateScoreText():void
{
txtScore.text = ("Score: " + currentScore); // set the text property of the txtS
trace("Score text updated");
}

These functions should be fairly self-explanatory, based off of the theory we


discussed earlier. If you have any questions about it, feel free to leave a
comment!
If you want check out the source file, you can find it here.
Hopefully this has given you a solid understanding of how saving and loading
works in AS3. If youre looking for another source to learn about the
SharedObject, you might want to check out this post by Michael James
Williams; or, if youre feeling ambitious you can try reading Adobes official
reference doc on it, here, for much more technical information. Try expanding
this topic to apply to your other games, maybe even to save your score in
thePong tutorial ;-)

You might also like