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 has quit. Unity provides the PlayerPrefs
feature to allow a game to store and retrieve data, between the different game playing sessions.
This recipe builds upon the previous recipe. In case you haven't completed the previous recipe, we have included a Unity
package named game_scoreStaticVariables
in the the 1362_10_05
folder. In order to follow this recipe using this package, you must do the following:
To save and load the player data using PlayerPrefs
, follow these steps:
Player
.UpdateScoreText
by replacing the Start()
method with the following:void Start(){ Text scoreText = GetComponent<Text>(); int scoreCorrect = PlayerPrefs.GetInt("scoreCorrect"); int scoreIncorrect = PlayerPrefs.GetInt("scoreIncorrect"); int totalAttempts = scoreCorrect + scoreIncorrect; string scoreMessage = "Score = "; scoreMessage += scoreCorrect + " / " + totalAttempts; scoreText.text = scoreMessage; }
IncrementCorrectScore
by replacing the Start()
method with the following code:void Start () { int newScoreCorrect = 1 + PlayerPrefs.GetInt("scoreCorrect"); PlayerPrefs.SetInt("scoreCorrect", newScoreCorrect); }
IncrementIncorrectScore
by replacing the Start()
method with the following code:void Start () { int newScoreIncorrect = 1 + PlayerPrefs.GetInt("scoreIncorrect"); PlayerPrefs.SetInt("scoreIncorrect", newScoreIncorrect); }
We had no need for the Player
class, since this recipe uses the built-in runtime class called PlayerPrefs
, provided by Unity.
Unity's PlayerPrefs
runtime class is capable of storing and accessing information (the string, int, and float variables) in the user's machine. Values are stored in a plist
file (Mac) or the registry (Windows), in a similar way to web browser cookies, and therefore, remembered between game application sessions.
Values for the total correct and incorrect scores are stored by the Start()
methods in the IncrementCorrectScore
and IncrementIncorrectScore
classes. These methods use the PlayerPrefs.GetInt("<variableName>")
method to retrieve the old total, add 1
to it, and then store the incremented total using the PlayerPrefs.SetInt("<variableName>")
method.
These correct and incorrect totals are then read each time the scene0_mainMenu
scene is loaded, and the score totals displayed via the UI Text object on the screen.
3.141.192.183