While the previous recipe illustrates how static properties allow a game to "remember" values between different scenes,
those values are "forgotten" once the game application has quit. Unity provides the PlayerPrefs
feature to allow a game to store and retrieve data between different game-playing sessions.
This recipe builds upon the previous recipe. In case you haven't completed the previous recipe, we have included a complete project named BlueSpheres-static
in the 0423_07_05
folder. In order to follow this recipe, make a copy of that folder as your starting point.
To save and load player data, follow these steps:
BlueSpheres-static
project and delete the Player
C# script.MenuStart
C# script by replacing the OnGUI()
method with the following code (the if
statement is to be changed):private void OnGUI() { string rules = "Easiest Game Ever -- Click the blue spheres to add points and advance levels."; GUILayout.Label(rules); if(PlayerPrefs.HasKey("username")) WelcomeGUI(); else CreatePlayerGUI(); }
MenuStart
C# script by replacing the ResetGameData()
method with the following code:private void ResetGameData() { PlayerPrefs.DeleteAll(); playerNameField = DEFAULT_PLAYER_NAME; }
MenuStart
C# script by replacing the first line of the WelcomeGUI()
method with the following:string welcomeMessage = "Welcome, " + PlayerPrefs.GetString("username") + ". You currently have " + PlayerPrefs.GetInt("score") + " points.";
Player.username = playerNameField; Player.score = 0;
And replace them with:
PlayerPrefs.SetString("username", playerNameField); PlayerPrefs.SetInt("score", 0);
SphereClick
C# script by replacing the ONGUI()
and OnMouseDown()
methods with the following code:private void OnGUI(){ GUILayout.Label( "Score: " + PlayerPrefs.GetInt("score") ); } private void OnMouseDown() { if( gameObject.CompareTag("blue") ){ int newScore = 50 + PlayerPrefs.GetInt("score"); PlayerPrefs.SetInt("score", newScore); } Destroy(gameObject); GotoNextLevel(); }
MenuEnd
C# script by replacing the first two lines of the OnGUI()
method with the following:GUILayout.Label("Congratulations " + PlayerPrefs.GetString("username")); GUILayout.Label("You have finished the game, score = " + PlayerPrefs.GetInt("score"));
All we needed to do was to change our code to take advantage of Unity's PlayerPrefs
Runtime
class. This class is capable of storing and accessing information (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.
For more information on PlayerPrefs
, see Unity's online documentation at http://docs.unity3d.com/Documentation/ScriptReference/PlayerPrefs.html.
3.145.109.234