Как я могу сохранить рекорд для 2D-игры - PullRequest
0 голосов
/ 03 мая 2019

У меня есть скрипт, который не сохраняет рекорды автоматически, и до того, как я нажму кнопку перезагрузки, мой рекорд был сохранен без кода.Я хочу сохранить рекорд, даже если игрок перезапустит игру. Это мой код для 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
    }
}

Ответы [ 2 ]

1 голос
/ 03 мая 2019

У вас проблемы с ключами, используемыми 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);

    }
}
0 голосов
/ 03 мая 2019

Как отметил Draco18s

, вы не должны использовать префы игроков для сохранения игровых данных (например, рекордов).

Вот как вы можете сохранить ихв файле JSON, если вы хотите.Это также добавляет больше гибкости в случае, если вы хотите добавить такие вещи, как десятка лучших или что-то в этом роде.

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);
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...