Search code examples
c#unity-game-engineunity3d-editor

What is the problem with this CSharp code (Unity) for highscore counting (the higshscore system is acting like a "normal" score counting system)?


I am making a gaming with Unity and I try to add highscore to my game, but the highscore always resets to 0. The highscore acts like an other score counting mechanism.

Here is the code:

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

public class Score : MonoBehaviour
{
    public Text ScoreText;
    private float score;


    public Text highScore;

    void Start()
    {
        highScore.text = PlayerPrefs.GetInt("HighScore", 0).ToString();
       
    }
    // Update is called once per frame
    void Update()
    {
        if (GameObject.FindGameObjectWithTag("Player") != null)
        {

            score += 1 * Time.deltaTime;
            ScoreText.text = ((int)score).ToString();

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

        }
    }
} 

The highscore counting part does not work properly. It always reset to 0 if I start a new game.


Solution

  • It seem there is HighScore and Highscore with s difference capitally in your code