How To Save Score In Unity
Solution 1:
In your update method try adding something to your code where you are detecting Escape Press.
if (Input.GetKeyDown(KeyCode.Escape)){
PlayerPrefs.setInt("Score", Int32.Parse(Score.text));
//Verify property is savedIntscoreTest= PlayerPrefs.getInt("Score");
Debug.Log(scoreTest);
Application.Quit();
}
Good Luck
Solution 2:
I think this is not the right way to save/load your score by doing operations on the Text.text
directly.
If you want to save and load your score, make a separate variable score
to store your score, then use your score in your UI Elements.
For example, this explains how you save scores at runtime:
publicclassScore: MonoBehaviour {
publicint score = 0;
// Use this for initializationvoidStart () {
// get the score when this gameObject initialized
score = PlayerPrefs.GetInt("Player Score");
}
// Update is called once per framevoidUpdate () {
// this is how you set your score to PlayerPrefsif (Input.GetKeyDown(KeyCode.Escape)) {
PlayerPrefs.SetInt("Player Score", score);
}
}
// this is an public function to be used // outside of the class to update scorepublicvoidUpdateScore(int amount) {
score += amount;
}
}
And use your score in your UI class:
publicclassDisplayScore : MonoBehaviour {
public Text scoreText;
public Score playerScore;
// Use this for initializationvoidStart () {
// get your Score component here or just drag it in inspector
}
// Update is called once per framevoidUpdate () {
// this updates the score at every frame
scoreText.text = playerScore.score.ToString();
}
}
don't forget using UnityEngine.UI
, saving/loading score in this way will be much easier.
Usually, you don't need to call PlayerPrefs.Save()
since the data will be automatically written to disk when the game quits (it calls automatically in OnApplicationQuit()
), but you may want to call it at certain point (i.e checkpoints) in case of program crushes or other unexpected situations.
Solution 3:
You should have a kind of a GameManager
class where you store everything you need to remember in appropriate attributes
. When you start the game you create an instance of the GM and reference to this object in the game logic. Things like the Score should be stored and processed within the GM. That way you can make sure to 'save' your score while the game is alive.
Post a Comment for "How To Save Score In Unity"