Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question PlayerPrefs is not saving the highscore, whenever i start new game the highscore updated will be 0.

Discussion in 'Scripting' started by ShivaprasadKM, Oct 7, 2022.

  1. ShivaprasadKM

    ShivaprasadKM

    Joined:
    May 11, 2022
    Posts:
    9
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using TMPro;
    using UnityEngine.SceneManagement;
    public class GameManager : MonoBehaviour
    {
    public static GameManager instance;
    [SerializeField]
    private GameObject _startPanel, _scoreObject, _endPanel, _player;
    [SerializeField]
    private TMP_Text _scoreText, _endScoreText, _highScoreText;
    private int _score;
    private int _Score
    {
    get
    {
    return _score;
    }
    set
    {
    StartCoroutine(UpdateText(value, _scoreText));
    _score = value;
    }
    }
    private int _endScore;
    private int _EndScore
    {
    get
    {
    return _endScore;
    }
    set
    {
    StartCoroutine(UpdateText(value, _endScoreText));
    _endScore = value;
    }
    }
    private int _highScore;
    private int _HighScore
    {
    get
    {
    return _highScore;
    }
    set
    {
    StartCoroutine(UpdateText(value, _highScoreText));
    _highScore = value;
    }
    }
    IEnumerator UpdateText(int finalValue, TMP_Text currentText)
    {
    int currentValue = int.Parse(currentText.text);
    int diff = (int)((finalValue - currentValue) * 0.01f);
    while (currentValue < finalValue)
    {
    currentValue += (diff > 0 ? diff : Random.Range(0, 5));
    currentText.text = currentValue.ToString();
    yield return new WaitForSeconds(0.01f);
    }
    currentText.text = finalValue.ToString();
    }
    private void Awake()
    {
    if (instance == null)
    instance = this;
    else
    Destroy(gameObject);
    }
    private void Start()
    {
    _startPanel.SetActive(true);
    _player.SetActive(false);
    _scoreObject.SetActive(false);
    _endPanel.SetActive(false);
    Camera.main.GetComponent<CameraFollow>()._canFollow = false;
    _Score = 0;
    _endScore = 0;
    _highScore = 0;
    UpdateHighScore();
    }
    public void UpdateScore(int currentScore)
    {
    _Score = currentScore;
    }
    public void GameStart()
    {
    _startPanel.SetActive(false);
    _scoreObject.SetActive(true);
    _player.SetActive(true);
    Camera.main.GetComponent<CameraFollow>()._canFollow = true;
    }
    public void GameEnd()
    {
    Destroy(_player, 2f);
    Camera.main.GetComponent<CameraFollow>()._canFollow = false;
    _scoreObject.SetActive(false);
    _endPanel.SetActive(true);
    _EndScore = _Score;
    int highScore = PlayerPrefs.HasKey("HighScore") ? PlayerPrefs.GetInt("HighScore") : _Score;
    if (_Score > highScore)
    {
    highScore = _Score;
    }
    _HighScore = highScore;
    }
    void CheckHighScore()
    {
    if
    (_Score > PlayerPrefs.GetInt("highScore",0))
    {
    PlayerPrefs.SetInt("highScore", _Score);
    }
    }
    void UpdateHighScore()
    {
    _highScore = _HighScore; { PlayerPrefs.GetInt("_HighScore", 0); };
    }

    public void GameQuit()
    {
    #if UNITY_EDITOR
    UnityEditor.EditorApplication.isPlaying = false;
    #endif
    Application.Quit();
    }
    public void GameRestart()
    {
    UnityEngine.SceneManagement.SceneManager.LoadScene(1);
    }

    public void Gomainmenu()
    {
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex - 1);
    }
    }
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,507
    This is not related to Visual Scripting. I'll move your post to the Scripting forum.

    Please edit your post to use code-tags for code and not plain text. Also, please put a little more effort into describing the problem, don't just try to cram it into the post title.

    Thanks.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,713
    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    You may edit your post above.

    I highly recommend NOT sprinkling PlayerPrefs calls through your code like so much spilled sand, because it is highly prone to typos and confusion, both of which cause failure.

    Instead, make an proper central place to track such things, such as this pattern:

    https://gist.github.com/kurtdekker/01da815d2dfd336a925ae38019c3a163

    Useful for a relatively small number of simple values.

    If you just need a single high score / low time tracker, here's one:

    Tracking simple high score / low time single-entry leaderboard:

    For the highest score: https://pastebin.com/VmngEK05

    Usage:

    Code (csharp):
    1. TheBest.RecordScoreIfHigher( lastGamePlayScore);
    For the lowest time: https://pastebin.com/A7GC76uQ

    Usage:

    Code (csharp):
    1. TheBest.RecordTimeIfLower( lastGamePlayTime);
    To retrieve the best score or time, use one of these:

    Code (csharp):
    1. int bestScore = TheBest.BestScore;
    Code (csharp):
    1. float bestTime = TheBest.BestTime;
    Full usage example:

    https://pastebin.com/ygFAvNsM

    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.
    BE PERFECT IN EVERYTHING YOU DO HERE!!

    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!
     
  4. ShivaprasadKM

    ShivaprasadKM

    Joined:
    May 11, 2022
    Posts:
    9
    Thank you Sir, I Will learn from my mistakes. I will be desciplined in whatever I do from now on.