The PlayerPrefs class stores information directly to your hard drive. There are two main types of functions, Set and Get. These are divided into SetInt, GetInt, SetFloat, GetFloat, SetString, GetString, depending on the type of variable you want to store.
Let's say I want to store to the disk that the player has reached a score of 150.
To store a certain variable to the hard disk, you can do this:
PlayerPrefs.SetInt("Score", 150);
Note that the function takes two parameters. The first is the key, and it is used to identify
the information stored at a later time.
Later in the game, I want to be able to recall the score that the player has achieved earlier, and print it to the console. To do this I'm going to use the GetInt function.
print(PlayerPrefs.GetInt("Score"));
This will effectively print out 150 to the console. The same method works with floats and strings:
PlayerPrefs.SetString("My favourite fruit", "Pineapple");
print("My favourite fruit is " + PlayerPrefs.GetString("My favourite fruit"));
PlayerPrefs.SetFloat("Pi", "3,14159265");
print("The value of Pi is " + PlayerPrefs.GetString("Pi"));
Using this method you can store information easily such as currency or items, but doing so will probably be very tedious if you have a lot of items. In any case, let's say your character buys an item from a NPC, you'll want to do something like this:
PlayerPrefs.SetString("Powerful Weapon", "Powerful Weapon");
To later check if the player has this item in the inventory, you can use another PlayerPrefs function, PlayerPrefs.HasKey. This will return true if the key exists in the preferences.
if(PlayerPrefs.HasKey("Powerful Weapon")) {
//Hide item from shop
}
To delete an item from your inventory, you can use:
PlayerPrefs.DeleteKey("Useless Weapon");
To delete every item in your preferences:
PlayerPrefs.DeleteAll();
Hope I helped.
Awesome! Thanks a lot this will be very handy indeed. Gotta love Unity!
– HHameline