I've been trying to get my head round player prefs, and want to load the last level I was on when restarting a stand alone game. Not sure I've really grasped it, so I'll outline what I think is right, in the hope that someone will kindly say whether I'm right or wrong.
I've got the following javascript but don't know where I should save it or which game item to attach it to:
static var levelvar: int;
//saving playerPrefs
function saveLevels()
{
PlayerPrefs.SetInt("SavedLevel",levelvar);
}
//geting playerPrefs
function getScores()
{
PlayerPrefs.GetInt("savedLevel");
}
Presumably (I think. Please tell me if I'm wrong) in the script that moves me from level 1 to level 2 I include something like
And then, if I close the game whilst still on level 2, on re-opening the game later, in the first code to run (what would that be?) I add something like
function getScores()
{
PlayerPrefs.GetInt("savedLevel");
}
if savedLevel== 2;
Application.LoadLevel (2);
I've got two parts to this single question about player prefs.
Are the above scripts right. If not, what would be right?
Where are these scripts actually put?
Could someone please advise me if the above works, or if I've completely lost the plot and got it all wrong.
When you use GetInt you have to assign it to something.
e.g.
levelToLoad = PlayerPrefs.GetInt("savedLevel");
Just calling GetInt wont do anything...
If you wanted to load a saved level at the start of a game you can put the GetInt directly inside the Application.LoadLevel() argument because that function returns an int.
To test that you've actually got a saved level you can use the HasKey funtion like so:
if(PlayerPrefs.HasKey("savedLevel")){
// there is a saved level, load that one
Application.LoadLevel(PlayerPrefs.GetInt("savedLevel"));
}else{
// no saved level, load the first one
Application.LoadLevel(1);
}