Time for action – saving data with PlayerPrefs
We're finally ready to save and load data to the player's collection class. For this, we'll be using Unity's PlayerPrefs
class in code.
Open the
PlayerCollection.cs
file in your code editor and add the following lines to yourCollectCoin
function:public void CollectCoin() { totalCoins++; print(totalCoins); PlayerPrefs.SetInt("TotalCoins", totalCoins); }
It's as simple as that! Let's examine what this new line actually does. We're calling the
SetInt
function from thePlayerPrefs
class because the data we're saving is an integer value. However,PlayerPrefs
also contains functions to save floating-point values and strings.No matter what kind of data you're saving, the parameters for the saving function are generally the same. The first value is a text string that represents a key or a way to label the data you're saving so that you can access it later.
The second parameter is the data you're saving with that key, be it an integer, string, or...