【问题标题】:How can I save the high score for a 2D game如何保存 2D 游戏的高分
【发布时间】:2019-05-03 13:51:36
【问题描述】:

我有一个不会自动保存高分的脚本,在我按下重新启动按钮之前,我的高分在没有任何代码的情况下保存了。我希望即使玩家重新开始游戏也能保存高分。这是我的 SCORE 代码:

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

public class Score : MonoBehaviour
{
    public int score;
    public Text ScoreText;
    public int highscore;
    public Text highScoreText;


    void Start()
    {
        highscore = PlayerPrefs.GetInt("HighScore: " + highscore);
    }

    void Update()
    {
        ScoreText.text = "Score: " + score;
        highScoreText.text = highscore.ToString();
        if (score > highscore)
        {
            highscore = score;

            PlayerPrefs.SetInt("HighScore: ", highscore);
        }
    }
    void OnTriggerEnter(Collider other)
    {
        Debug.Log("collider is working");
        if (other.gameObject.tag == "Score: ")
        {
            score++;
        }
    }
}

这是重启按钮的代码:

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class RestartGame : MonoBehaviour
{
    public void RestartsGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name); // loads current scene
    }
}

【问题讨论】:

  • 你不需要在 UPDATE 函数中使用 PlayerPrefs.setInt。
  • 请注意,您不应该使用玩家偏好来保存游戏数据(例如高分),而是您自己的文件。 PlayerPrefs 适用于播放器的音量、静音状态或首选控制方案等。

标签: c# unity3d 2d-games


【解决方案1】:

PlayerPrefs使用的密钥有问题:

void Start()
{
    highscore = PlayerPrefs.GetInt("HighScore");
}

void Update()
{
    ScoreText.text = "Score: " + score;
    highScoreText.text = highscore.ToString();
    if (score > highscore)
    {
        highscore = score;

        PlayerPrefs.SetInt("HighScore", highscore);

    }
}

【讨论】:

    【解决方案2】:

    如 Draco18s 所述

    您不应该使用玩家偏好来保存游戏数据(例如 高分)。

    如果需要,您可以将其保存在 json 文件中。如果您想添加诸如前 10 名之类的内容,它还增加了更多的灵活性。

    using UnityEngine;
    using System.IO;
    
    public class HighestScoreJson
    {
        /// <summary>
        /// //Returns the path to the highestScoreFile
        /// </summary>
        /// <returns></returns>
        public static string GetPathToHighestScore() {
            return Path.Combine(Application.persistentDataPath, "HighestScore.json"); //You can look for info about the unity streamingAssets folder in the unity documentation
        }
    
        /// <summary>
        /// Get the highestScore
        /// </summary>
        /// <returns></returns>
        public static HighestScore GetHighestScore() {
            string path = GetPathToHighestScore();
    
            if (!File.Exists(path)) //Checks if the file exists
            {
                HighestScore highestScore = new HighestScore();
                string jsonObj = JsonUtility.ToJson(highestScore);
                //Debug.Log("SavedJsonFile: " + jsonObj);
                FileInfo defaultFile = new FileInfo(path);
                defaultFile.Directory.Create(); // If the directory already exists, this method does nothing.
                File.WriteAllText(path, jsonObj);
            }
    
            string file = File.ReadAllText(path);
            HighestScore highestScoreJson = JsonUtility.FromJson<HighestScore>(file);
            //Debug.Log(highestScoreJson.highestScore); //here you can check the value on the debug if you want
            return highestScoreJson;
        }
    
        /// <summary>
        /// Save a new highestScore
        /// </summary>
        /// <param name="highestScore"></param>
        public static void SaveHighestScore(int highestScoreValue) {
        string path = GetPathToHighestScore();
        HighestScore highestScore = new HighestScore();
        highestScore.highestScore = highestScoreValue;
        string jsonObj = JsonUtility.ToJson(highestScore);
        //Debug.Log("SavedJsonFile: " + jsonObj);
        FileInfo file = new FileInfo(path);
        file.Directory.Create(); // If the directory already exists, this method does nothing.
        File.WriteAllText(path, jsonObj);
        }
    }
    
    /// <summary>
    /// This class holds the highestScore
    /// </summary>
    public class HighestScore
    {
        public int highestScore;
        //You can also create a list if you want with the top 10 or something like that
    }
    

    那你就这样用吧

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.UI;
    
    public class Score : MonoBehaviour
    {
        public int score;
        public Text ScoreText;
        public int highscore;
        public Text highScoreText;
    
    
        void Start()
        {               
            highscore = HighestScoreJson.GetHighestScore().highestScore; 
        }
    
        void Update()
        {
            ScoreText.text = "Score: " + score;
            highScoreText.text = highscore.ToString();
            if (score > highscore)
            {
                highscore = score;
            HighestScoreJson.SaveHighestScore(highscore);
            }
        }
        void OnTriggerEnter(Collider other)
        {
            Debug.Log("collider is working");
            if (other.gameObject.tag == "Score: ")
            {
                score++;
            }
        }
    
    }
    

    如果您取出更新并仅在分数变化时调用更改您的文本,您可能可以优化您的通话。

    void Update() //Don't need it
    {
    }
    void OnTriggerEnter(Collider other)
    {
        Debug.Log("collider is working");
        if (other.gameObject.tag == "Score: ")
        {
            score++;
            ScoreText.text = "Score: " + score;
            highScoreText.text = highscore.ToString();
            if (score > highscore)
            {
               highscore = score;
               HighestScoreJson.SaveHighestScore(highscore);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-19
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多