Playerprefs resetting after quit

Hey! I’m having a problem with my code. My game is currently using 2 scripts, a GameManager (attaches to camera) and a SunScript (attached to a prefab (Sun) that is instantiated every 1 second onto the screen). When you click on the Sun, it destroys the gameObject and adds 10 points to your score, which I save using playerprefs, and then displays it using OnGUI.

The problem: when I quit the application and re-open, it displays the correct amount, but when I click on a Sun, it resets the counter. PLEASE HELP!

Here is the GameManager script:

using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {
	public GameObject sunPrefab;
	private float rateDrop = 2f;
	public static float totalCurrency;
	public static float collectAmount = 152f;
	public GUISkin skin;

	void Start(){
		GenerateSun();
		Debug.Log(PlayerPrefs.GetFloat("Total Currency"));
	}

	void InstantiateSun(){
		Instantiate (sunPrefab, new Vector2(Random.Range(-6.0f, 0f), Random.Range(10.0f, 12.0f)), Quaternion.identity);
	}

	void GenerateSun(){
		InvokeRepeating ("InstantiateSun", 1f, rateDrop);
	}

	void OnGUI (){
		GUI.skin = skin;
		GUI.Label(new Rect(Screen.width/2 - 40, 10.0f, 40, 20), PlayerPrefs.GetFloat("Total Currency").ToString(), skin.GetStyle("Counter"));
	}

	void OnApplicationQuit(){
		PlayerPrefs.SetFloat("Total Currency", PlayerPrefs.GetFloat("Total Currency"));
	}
}

And here is the SunScript:

using UnityEngine;
using System.Collections;

public class SunScript : MonoBehaviour {
public GameObject particles;

void Update(){
	if(transform.position.y < -15.0f){
		Destroy(gameObject);
	}
}

void OnTriggerEnter(Collider other){
	if(other.transform.tag == "House"){
		Debug.Log("I hit the house!");
		Destroy(gameObject);
	}
}

void OnMouseDown(){
	Collect();
}

void Collect(){
	Instantiate (particles, transform.position, Quaternion.Euler(270,0,0));
	Debug.Log(PlayerPrefs.GetFloat("Total Currency"));
	GameManager.totalCurrency += GameManager.collectAmount;
	PlayerPrefs.SetFloat("Total Currency", GameManager.totalCurrency);
	Destroy(gameObject);	
}

}

You need to call PlayerPrefs.Save to save your changes.

Depending on your game, you might want to call this between levels (or during some other “pause” in the action)… or, if you don’t set prefs very often, you might be able to get away with saving after each and every change.

Figured it out! So the problem was caused by the prefab being instantiated and then destroyed. All I had to do was add the following to the SunScript:

void Start()
{
GameManager.totalCurrency = PlayerPrefs.GetFloat("Total Currency");
}

basically allows the instantiated object to recognize that a number already exists in “Total Currency”.