Groude Groude - 3 months ago 21
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

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()
    {
        DontDestroyOnLoad(transform.gameObject);
        timeSpendOnGame.GetComponent<Text>();
    }

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


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

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

    //Load when Opening
    public void OnEnable()
    {
        Debug.Log("Opening!");
        Load();
    }

    //Increment and Save on Exit
    public void OnDisable()
    {
        Debug.Log("Existing!");
        timesPlayed++; //Increment how many times opened
        Save(); //save
    }
}
Comments