Wednesday, October 1, 2014

Unity how to save and load game

Say if you want to save and load game you do as below,
let say you have 2 variable, 1 is the arraytimer1 (an array containing float), another variable is a String variable Category1, so first you create two function as below.
Do note by default you can only use PlayerPrefs but if you want to use PlayerPrefsX you need to create a new java script "PlayerPrefsX.js" and you copy paste the code from http://wiki.unity3d.com/index.php/ArrayPrefs2

function saveall()
{

        PlayerPrefsX.SetFloatArray("arraytimer1",arraytimer1);
        PlayerPrefs.SetString("Category1",Category1);
        

}
function loadall()
{

        arraytimer1PlayerPrefsX.GetFloatArray("arraytimer1");

        Category1 = PlayerPrefs.GetString("Category1");
}


To call the function, I would recommend you put the loadall in the function start, meaning when you start your app, it will load all the data into your game, and you only save your game when your application quit , so you put the saveall() in your function OnAPplicationQuit()

function Start () 
{

    loadall();

}

function OnApplicationQuit() 
{
    saveall();
}

No comments:

Post a Comment