Home > Mobile >  PlayerPref is not getting stored properly
PlayerPref is not getting stored properly

Time:06-19

Im new to programming. I was able to store the Highscore. Now i have the problem that its not working with the Money. I am trying to store the Money so even if the game gets closed it will still be saved. I watched alot of Videos about it but i am having kinda problems with understanding since its something new for me.

{
    public GameObject playButton;

    public GameObject Gameover;

    public GameObject ShopMenu;

    public Player player;
    public TMP_Text scoreText;

    public TMP_Text MoneyText;
    public int score;
    public int money;
    public TMP_Text highScore;

    private void Awake()
    {
        Application.targetFrameRate = 60;

        Pause();
    }

    public void play()
    {
        score = 0;
        scoreText.text = score.ToString();

        playButton.SetActive(false);
        Gameover.SetActive(false);
        ShopMenu.SetActive(false);

        Time.timeScale = 1f;
        player.enabled = true;

        pipes[] pipes = FindObjectsOfType<pipes>();

        for (int i = 0; i < pipes.Length; i  )
        {
            Destroy(pipes[i].gameObject);
        }

        highScore.text = PlayerPrefs.GetInt("HighScore", 0).ToString();

        if (score > PlayerPrefs.GetInt("HighScore", 0))
        {
            PlayerPrefs.SetInt("HighScore", score);
            highScore.text = score.ToString();
        }

        MoneyText.text = PlayerPrefs.GetInt("money").ToString();

        if (money != PlayerPrefs.GetInt("money"))
        {
            PlayerPrefs.SetInt("money", money);
            MoneyText.text = money.ToString();
        }
    }

    public void Pause()
    {
        Time.timeScale = 0f;

        player.enabled = false;
    }

    public void GameOver()
    {
        Gameover.SetActive(true);
        playButton.SetActive(true);
        ShopMenu.SetActive(true);

        highScore.text = PlayerPrefs.GetInt("HighScore", 0).ToString();

        if (score > PlayerPrefs.GetInt("HighScore", 0))
        {
            PlayerPrefs.SetInt("HighScore", score);
            highScore.text = score.ToString();
        }

        MoneyText.text = PlayerPrefs.GetInt("money").ToString();

        if (money != PlayerPrefs.GetInt("money"))
        {
            PlayerPrefs.SetInt("money", money);
            MoneyText.text = money.ToString();
        }

        Pause();
    }

    public void IncreaseScore()
    {
        score  ;
        scoreText.text = score.ToString();
        money  ;
    }
}

CodePudding user response:

It seems like your money value is always 0 as you do not initialize it. The same is about the score value. Try to add

money = PlayerPrefs.GetInt("money", 0);
score = PlayerPrefs.GetInt("HighScore", 0);

to your Awake() method

  • Related