Unity 3d 保存高分bug

Unity 3d Saving high score bug

我创建了一个简单的游戏,玩家在每个关卡中收集分数,关卡完成后会显示总高分。我最近学会了如何使用玩家偏好进行保存,并且我能够存储玩家在每个特定级别的高分。

这是玩家完成关卡时的照片:

这是它的代码:

 void Update()
{

    int tScore = PlayerPrefs.GetInt(SceneManager.GetActiveScene().name, 0);//it is adding the points with the highscore again for some reason 
    scoreDisplay.text = "TOTAL POINTS: "+ PlayerController.count.ToString();//display score 
    timeDisplay.text = "TIME LEFT: " + FindObjectOfType<TimeController>().timeText.text;//display remainder time 
    scorePoints = PlayerController.count;
    if (FindObjectOfType<TimeController>().minutes != 0)
    {
        timePoints = (FindObjectOfType<TimeController>().sec + 60)/2;
    }
    else
    {
        timePoints = FindObjectOfType<TimeController>().sec/2;
    }
    highScore = timePoints * scorePoints;
    highScores.text = "HIGH SCORE: " + highScore;

    if (tScore <= highScore)
    {
        PlayerPrefs.SetInt(SceneManager.GetActiveScene().name, highScore);
    }

}

我正在保存整个场景,以便保存特定级别的高分。我做的第一件事是使用 'GetInt' 作为 tScore 或如果有 none,则默认值为零,以获得玩家先前从同一级别得分的先前高分。然后简单地通过获取 scorePoints(我从代码中的另一个 class 'PlayerController.count' 获得)并将其与您在上面的代码中看到的剩余时间相乘来计算高分。然后我将 highScore 与之前相同级别的 highscore (tScore) 进行比较,如果它更高,它将覆盖为该级别的新 highScore。

这段代码大部分时间都有效,但出于某种原因,有时,已经计算出的那个场景的高分会再次加上分数(上图的例子,高分是 368,但是当我使用 GetInt,它再次添​​加点数,意思是 (368+16 = 384) 成为最高分(覆盖之前的最高分),这是错误的。有人能告诉我这有什么问题吗?

好的,我会尽力给出答案。请注意,我可能误解了您的要求。无论如何,我会创建一个简单的 MonoBehaviour,例如“ShowScore.cs”,它可以放置在场景中的任何位置(所以为什么不放在 canvas 上)。

using UnityEngine;

public class ShowScore : MonoBehaviour
{
    public UI.Text scoreDisplay;
    public UI.Text timeDisplay;
    public UI.Text highScores;
  
    public void GameOver()
    {
        string sceneName = SceneManager.GetActiveScene().name;
        int currentHighScore = PlayerPrefs.GetInt(sceneName, 0);
        TimeController timeController = FindObjectOfType<TimeController>();
    
        int scorePoints = PlayerController.count;
        int seconds = timeController.sec + timeController.minutes * 60;
        Debug.Log("timeController.sec: " + timeController.sec.ToString());
        Debug.Log("timeController.timeText.text: " + timeController.timeText.text);
        int timePoints = (int)(seconds/2f);
        int score = timePoints * scorePoints;

        scoreDisplay.text = "TOTAL POINTS: "+ scorePoints.ToString();
        timeDisplay.text = "TIME LEFT: " + seconds.ToString(); 
    
        if (score > currentHighScore)
        {
            PlayerPrefs.SetInt(sceneName, score);
            highScores.text = "HIGH SCORE: " + score.ToString();
        }
        else
        {
            highScores.text = "SCORE: " + score.ToString() + " (the HIGH SCORE is " + currentHighScore.ToString() + ")";
        }
    }
}

一旦触发结束触发器,我就会调用函数 GameOver()。祝你好运!