微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Unity 3d 保存高分错误

如何解决Unity 3d 保存高分错误

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

这是玩家完成关卡时的图片

enter image description here

这是它的代码

awk '                                        ##Starting awk program from here.
{
  for(i=1;i<=NF;i++){                        ##Traversing through all fields here.
    if($i~/^adam$/)         { $i="user_1" }  ##Checking if field is adam then set it to user_1 here.
    if($i~/^adam_acc$/)     { $i="user_3" }  ##Checking if field is adam_acc then set it to user_3 here.
    if($i~/^adam\.eve$/)    { $i="user_2" }  ##Checking if field is adam.eve then set it to user_2 here.
    if($i~/^adam\.eve_acc$/){ $i="user_4" }  ##Checking if field is adam\.eve_acc then set it to user_4 here.
  }
}
1                                            ##Printing current line here.
' Input_file                                 ##Mentioning Input_file name here.

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

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

解决方法

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

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()。祝你好运!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。