PlayerPrefs not saving after restarting level in editor
Hi,
For my skeet shooting game, all I want to do is keep track of the amount of coins the player has. So I set up a simple script that handles all the player's coins. Here it is:
private int pullMethod;
private int playerCoins;
void OnEnable()
{
EndlessDestroyer.moneyDiscDestroyed += MoneyDiscDestroyed;
}
void OnDisable()
{
EndlessDestroyer.moneyDiscDestroyed -= MoneyDiscDestroyed;
}
void LevelWonCoinEarnings()
{
playerCoins = playerCoins + 5; //adds coins after beating a level
SaveCoins();
}
void MoneyDiscDestroyed()
{
playerCoins = playerCoins + 10; //adds coins after destroying a money disc in endless
SaveCoins();
}
void SaveCoins()
{
PlayerPrefs.SetInt ("PlayerTotalCoins", playerCoins);
PlayerPrefs.Save();
print(PlayerPrefs.GetInt("PlayerTotalCoins"));
}
In the console I see the coins adding up as I shoot down the correct discs in the air, but whenever I restart the level, nothing saves. The next time I shoot down a disc, the total player coins have just reset back to 0.
I for the life of my cannot figure out why this isn't working. Like If I am being stupid, and the error in my code is staring me right in the face, then please tell me haha. Help!
Thank you
Answer by corn · Jun 24, 2016 at 04:12 PM
You correctly save the data, but you never retrieve it. When you restart the level, playerCoins is equal to 0. The correct data is stored in PlayerPrefs, but you need to explicitly assign it to playerCoins, otherwise the script is going to start with 0, increment it as you shoot discs, and erase the old data.
void OnEnable()
{
playerCoins = PlayerPrefs.GetInt("PlayerTotalCoins");
EndlessDestroyer.moneyDiscDestroyed += MoneyDiscDestroyed;
}
@corn is correct but pass a default value to it otherwise the first time the game is run it will throw an error because the key will not yet exist. Like this
playerCoins = PlayerPrefs.GetInt("PlayerTotalCoins", 0);
Thank you so much! This worked. I wasn't aware of how this truly worked I guess.
Your answer
Follow this Question
Related Questions
I'm having a problem while jumping an object in Unity 5 0 Answers
PlayerPrefs returns nothing 0 Answers
Save player rotation in playerprefs c# 2 Answers
need help with code please 1 Answer
Playerpref Saving Lag 1 Answer