Saving data between scenes and games using PlayerPrefs
While the previous recipe illustrates how the static properties allow a game to remember values between different scenes, these values are forgotten once the game application is exited. Unity provides the PlayerPrefs feature to allow a game to store and retrieve data between the different game-playing sessions.
Getting ready
This recipe builds upon the previous recipe, so make a copy of that project and work from it.
How to do it...
To save and load the player data using PlayerPrefs
, follow these steps:
- Delete the C# script
PlayerData
. - Edit the C# script called
UpdateScoreText
by replacing theStart()
method with the following code:void Start(){ int scoreCorrect = PlayerPrefs.GetInt("scoreCorrect"); int scoreIncorrect = PlayerPrefs.GetInt("scoreIncorrect"); int totalAttempts = scoreCorrect + scoreIncorrect; string scoreMessage = "Score = "; ...