Thursday, July 26, 2012

How to save in unity.

Saving in unity is strange. the way that I have found to do it is by using player prefs.

so using player prefs when something happens that you want to save such as a player score you can use:


PlayerPrefs.SetInt("Player Score", 10);


then to access this saved information you can call

PlayerPrefs.GetInt("Player Score");


the string you use is irrelevant... you can use "myScore" or something else as long as you can remember and call the information again.

here's a test script you can play with. just attach it to the main camera or an empty object so that you can play around with it. the score should start out as "10" when you press set score it will set it to fifty. press get score and the scene will print out the new player score.


function Start () {
PlayerPrefs.SetInt("myScore", 10);
}


function Update () {


}


function OnGUI()
{
if(GUI.Button(Rect(10,10,200,200),"getScore"))
{
print (PlayerPrefs.GetInt("myScore"));
}

if(GUI.Button(Rect(300,10,200,200), "setScore"))
{
PlayerPrefs.SetInt("myScore", 50);
}
}


here are some other useful calls from the script reference


PlayerPrefs.SetFloat("Player Score", 10.0);
PlayerPrefs.GetFloat("Player Score");

PlayerPrefs.SetString("Player Name", "Foobar");
PlayerPrefs.GetString("Player Name");

No comments:

Post a Comment