Groude - 1 year ago 63
Android Question

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

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.

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

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

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

{
timesPlayed = PlayerPrefs.GetInt("timesPlayed");
}

public void OnEnable()
{
Debug.Log("Opening!");