0

I'm working on a script that gives player 5 points every second; And I want it to store the score using PlayerPrefs in Unity3d. I wrote the script, the current score works like it should, but Total Score using PlayerPrefs seem not to be working.

Here's my script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ScoreDataManager : MonoBehaviour {

    public Text txtScore;
    public static int score;
    public Text txtHighscore;
    public static int highscore;
    int newHighscore;

    int nameSize = 15;
    private float timer;

    void Start (){

        score = PlayerPrefs.GetInt("highscore");
    }
    void Update (){

        timer += Time.deltaTime;

        if (timer > 5f) {
            score += 5;

            timer = 0;
        }

        txtHighscore.text = string.Format("TOTAL POINTS: <size=" + nameSize + "><color=#00ffd8>{0}</color></size>", PlayerPrefs.GetInt("highscore"));
        txtScore.text = string.Format("CURRENT POINTS: <size=" + nameSize + "><color=#00ffd8>{0}</color></size>", score.ToString());

        StoreHighscore (newHighscore);
    }
    void StoreHighscore (int newHighscore)
    {
        int oldHighscore = PlayerPrefs.GetInt ("highscore", 0);
        if (newHighscore > oldHighscore) 
        {
            PlayerPrefs.SetInt ("highscore", newHighscore);
            txtHighscore = txtScore;
        }
        PlayerPrefs.Save ();

        Debug.Log ("Current points: " + score.ToString ());
        Debug.Log("Total points: " + PlayerPrefs.GetInt("highscore"));
    }
}

Any help would be appreciated!

papi
  • 379
  • 7
  • 25
  • before StoreHighscore (newHighscore); where are you setting the new value of newHighscore? it seems to be 0 for me everytime – jace Sep 07 '17 at 03:36
  • Yeah, I figured it out. Just had to add "PlayerPrefs.SetInt("highscore", score); and PlayerPrefs.Save; – papi Sep 07 '17 at 03:42
  • Works now. But at the same time, after restarting, Current Points do not start from zero. I think I know how to fix it though. – papi Sep 07 '17 at 03:43
  • Saving playerprefs in update function is a very inefficient and costly process. Playerprefs writes to storage disk which takes time. You can just retrieve the highscore from playerprefs when the game is launched to a static variable. During gameplay use the static variable value. When you are exiting the game or a level is finished, save the static variable value to playerprefs. – ZayedUpal Sep 07 '17 at 05:09
  • @ZayedUpal I've been playing with my code for a while now. Confused as hell. Can you provide example code for me how you would do it? I would appreciate it. – papi Sep 07 '17 at 05:22
  • I would do something like this: https://pastebin.com/9PFpMpqn – ZayedUpal Sep 07 '17 at 06:20

0 Answers0