Groude Groude - 1 year ago 116
Android Question

Unity Auto Save and loading just a simple variable

I want to create somehow a statistics scene that shows some information about how much the user interacted with the game

Answer Source

Doing this inside OnApplicationFocus and OnApplicationPause function would have been better but there are many instances where these functions are not called and this also depends on the platform. Doing it inside OnEnable and OnDisable functions should do it because these functions are guaranteed to be called.

Although, you will need to put DontDestroyOnLoad(transform.gameObject); in the Awake function to make sure that OnEnable and OnDisable are not called when new scene is loading during gameplay.

Problems with your code:

1.You are saving test key as an int with PlayerPrefs.SetInt("test", timesPlayed); but then loading the test key as a float with PlayerPrefs.GetFloat("test").

2.Even when loading it, you are not assigning the loaded value to anything. timesPlayed = PlayerPrefs.GetInt("timesPlayed"); should do it.

3.Finally, you are not saving it on exist. Not only this, you are not even calling the Save() and Load() function from anywhere. You need to know what functions gets called when Unity loads and unloads.

Below is a simple amount of times opened counter based on your script. Create a GameObject and the script below to it. You can now extend this to include other functions.

public class OpenCounter : MonoBehaviour
    int timesPlayed;
    public Text timeSpendOnGame;

    void Awake()

    void Start()
        timeSpendOnGame.text = "" + timesPlayed;

    public void Save()
        PlayerPrefs.SetInt("timesPlayed", timesPlayed);

    public void Load()
        timesPlayed = PlayerPrefs.GetInt("timesPlayed");

    //Load when Opening
    public void OnEnable()

    //Increment and Save on Exit
    public void OnDisable()
        timesPlayed++; //Increment how many times opened
        Save(); //save
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download