Player prefs in Unity
Objective: Use Unity’s PlayerPrefs methods to save simple game data
In my endless runner DangryRun, I do not have a lot of data to store that needs to be recovered, so I took leverage of Unity’s PlayerPrefs class.
It allows you to save floats, ints and strings for player preferences that can be easily retrieved. I use this for the player score, their display name, the preferred game speed and a few others.
Using player prefs allows me to quickly store this data and update it when needed. For instance, saving the game speed that I allow the player to set in the optional menu. Depending on the three options that are chosen I then set the Timescale of the game.
Once the player clicks the speed they want to try I then use Playerprefs to save the game speed.
Timescale is a float so I am storing the speed as a float. When the game scene is loaded and the player is created, I then set the timescale to the speed stored in the PlayerGameSpeed playerprefs variable.
I first check whether there is a PlayerPrefs key with the name of PlayerGameSpeed. If it exists then I set the Time.timescale to the stored speed. If it is not there, then I set the Time.timescale to 1f.
That’s it for using PlayerPrefs. You can see more information about player prefs here.