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

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;
}