- Home /
Using PlayerPrefs to Imitate a players inventory
Hello, I don't really have any code yet, because to be honest I don't really know where to start. I was hoping that someone could actually point me to a good resource for how PlayerPrefs worked. Also if anyone would be willing to past a little bit of pseudocode or something so I can understand the basics of PlayerPrefs that would be great. What I want to do is imitate a players inventory and when the player clicks on the shop the items the player already has in their inventory will not display in the shop. But since I don't have the database set up yet i thought PlayerPrefs would be the way to do it does that sound about right?
Thanks, Hans Unity Newb
Answer by Bumbaz 1 · Apr 28, 2011 at 09:16 PM
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!