As a player progresses through our games, we need to be able to store their progress values, whether they are their score, current level, health, ammunition, and so forth:
To save this data, we make use of the Unity function
PlayerPrefs
.To store data, we use
PlayerPrefs.Set
followed by the data type we are using to store data. So,PlayerPrefs.SetInt
is the function for an integer.We then provide the reference name of the value we are storing followed by the actual variable that we would like to store. The following line of code is an example:
PlayerPrefs.SetInt("level", level);
To retrieve and, therefore, load the stored data, we make use of
PlayerPrefs.Get
followed by the data type that we are loading, then the reference name, and lastly, we specify a value to assign should no existing data be saved.Thus, to load the level data, we use the following line of code:
PlayerPrefs.GetInt("level", 1);
Adding the second parameter is known as exception handling, whereby we respond...