Search code examples
androidactionscript-3air

How do I automatically save my preferences on as3?


How do I automatically save my game and load the game with a button in actionScrpt3?

I am developing a game and I want to leave the game when I can save it automatically and that when I start it again, a button appears in the main menu and it loads the game where it was saved

Thank You


Solution

  • Simplest way would be to save a file onto the application storage directory on a specific action (like on a save button click, or after a certain time period etc).

    Depending on your needs you could choose to save a simple text file, an XML file or even a JSON file, whichever suits your need. Simply insert your data into the file and save it then to the application storage directory.

    Following is the code to save a simple text file onto the application storage directory:

    var dataToSave:String = "Some data to be saved.....";
    var file:File = File.applicationStorageDirectory.resolvePath("savedUserInfo.txt");
    var stream:FileStream = new FileStream();
    stream.open(file, FileMode.WRITE);
    stream.writeUTFBytes(dataToSave);
    stream.close();
    

    You can put the above code inside a method and call in when you want to save data.

    And on application startup each time you could check if the file exists and load in the data and perform your actions accordingly to resume/restore game state.

    Here's the code to load the file:

    var file:File = File.applicationStorageDirectory.resolvePath("savedUserInfo.txt");
    if(file.exists){
        var stream:FileStream = new FileStream();
        stream.open(file, FileMode.READ);
        var data:String = stream.readUTF(); 
        stream.close();
        //perform your operations to restore/resume game state
    }else{
        //there was no saved game file. Resume normal game bootup.
    }
    

    As I said, this maybe the simplest way to save a file onto the application storage directory. Depending on your needs, you may want to choose a more code friendly format like JSON or XML to save and load your data. Of course there will be some code changes based on what format you decide.

    Also, make sure you have permissions set to write the file. To do this you need to add the following, in particular the "WRITE_EXTERNAL_STORAGE" line, to your application descriptor.

    <android>
        <manifestAdditions><![CDATA[
            <manifest android:installLocation="auto">
                <uses-permission android:name="android.permission.INTERNET"/>
                <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
            </manifest>
        ]]></manifestAdditions>
    </android>
    

    Hope this helps. Cheers.