Question Regarding PlayerPrefs

Hi all, I just stumbled upon PlayerPrefs class as a way to store data across multiple games session. From what I have known (please correct me if I am wrong), PlayerPrefs works exactly like a dictionary, having key value pairs. In that case, why not just use dictionaries instead?

Dictionaries are an “in-memory” representation of data, Player prefs are an “on-disc” representation (for persitance). You could serialize/store/write dictionary data into a file too. But AFAIK Unity does not support dictionary serialization out of the box (don’t know if that changed recently). So you would have to do it manually anyway.
However, Playerprefs are not meant to store huge level data or similar. Since the stuff is stored in the registry under Windows this is not the place for anything complex. In most cases you want to roll your own savegame solution or use a premade one (AssetStore).

1 Like

Can you explain a bit more on what you meant by this?

A dictionary is used during “runtime” to store and access key value pairs. The player prefs are not meant for real time access. They are more for saving data on disk when the player closes the game (like a savegame). So both are pretty different concepts and used in very different contexts/situations.
So your assumption “PlayerPrefs works exactly like a dictionary” is wrong IMO. They share the concept of key value pairs but they are not interchangeable as they are used for quite different reasons and in different usecases.
So the answer to your question “why not just use dictionaries instead?” is that dictionaries can’t provide what player prefs are used for (storing data on disk). You should not mix both concepts up. Each has it’s respective use but they are not used in the same conctext. Is that clear now?

1 Like

The point of PlayerPrefs is the data is preserved between game sessions, in fact if you’re using PlayerPrefs for anything else you should probably use something else instead. You put data in PlayerPrefs, close the game, shut off the computer, mail the computer across the country, and then launch the game again, and the data in PlayerPrefs is exactly as saved last time you ran the game.

With a dictionary, whatever you put in there is lost as soon as the player closes the game.

The real cool part of PlayerPrefs is that it is platform agnostic. If you rolled your own dictionary like system for saving data to disk, you’d have to implement it differently for certain platforms. But Unity took care of all that for you with PlayerPrefs, giving you a single interface no matter your build target.

1 Like

I see. Thanks Joe and exiguous for the super detailed explanations!

1 Like