- Home /
[ANDROID]saving data with playerprefs
Hello.
I'm making an android 2d runner game and I'm trying to save some data periodically such as high scores, total distance run, number of games played, average distance per game etc.
I'm attempting to use PlayerPrefs to do this but the problem is (I think...) that my saved keys are all rest to 0 after the app is closed and restarted.
Here is an example of my game over routine where I attempt to save some data..
private void GameOver () {
renderer.enabled = false;
rigidbody.isKinematic = true;
totalNumberOfJumps+=numberOfJumps;
PlayerPrefs.SetFloat ("totalNumberOfJumps", totalNumberOfJumps);
PlayerPrefs.SetFloat ("NumberOfPlays", numberOfPlays);
GUIManager.SetTotalNumberOfJumps(totalNumberOfJumps);
GUIManager.SetNumberOfPlays(numberOfPlays);
totalDistanceRun += distanceTraveled;
PlayerPrefs.SetFloat ("totalDistanceTraveled", totalDistanceRun);
GUIManager.SetTotalDistanceRun(totalDistanceRun);
GUIManager.SetHighScore(highScore);
averageDistance = totalDistanceRun / numberOfPlays;
PlayerPrefs.SetFloat ("averageDistance", averageDistance);
GUIManager.SetAverageDistance(averageDistance);
if(score>highScore){
highScore = score;
PlayerPrefs.SetFloat("HighScore", highScore);
GUIManager.SetHighScore(highScore);
Debug.Log (highScore);
PlayerPrefs.Save();
}
enabled = false;
}
I then attempt to read the total number of jumps at the start of my game..
private void GameStart () {
PlayerPrefs.GetFloat ("totalNumberOfJumps", totalNumberOfJumps);
}
My totalNumberOfJumps variable is 0 where before the app was restarted it reflected the true number of jumps.
I can't get it to work in the Unity Editor or on Android.
What's the best way to debug PlayerPrefs on a device? Does PlayerPrefs return an error if you use GetFloat and the key does not exist?
Should I be using PlayerPrefs to store data such as this and if not, what are my alternatives?
I have no idea where PlayerPrefs stores it's data on Droid, I've read of a location but I can't find it on my rooted Galaxy S2. Does anyone know where I can find it?
Using Unity 4.2.1f4, Android 4.0.4
Edited to show full GameOver() function
Do you actually save the PlayerPrefs to disk at any point?
PlayerPrefs.Save() // http://docs.unity3d.com/Documentation/ScriptReference/PlayerPrefs.Save.html
Apologies for being vague. The PlayerPrefs are saved at the very end of my GameOver function of which a snippet is in my post. I'm saving quite a bit of info and most of it has been removed for clarity. I should have included the PlayerPrefs.Save(); line though. I will edit my code to show the full function.
Answer by Yury-Habets · Nov 18, 2013 at 06:39 PM
Hi,
You have to assign your variable to what was returned by GetFloat:
private void GameStart () {
totalNumberOfJumps = PlayerPrefs.GetFloat ("totalNumberOfJumps");
}
Second parameter is the default value assigned if "totalNumberOfJumps" is not set in PlayerPrefs.
$$anonymous$$any thanks, that works as I wanted it to.