保存分数,然后在高分中使用它

Saving the score, then using it in highscore

我有一个脚本,每 1 秒给你 1 分。

我想知道如何将分数保存为高分。我知道 PlayerPref,但我无法理解它。我还尝试了其他几种解释。

using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class score : MonoBehaviour
{
    private Text scoreText;
    private float PIPS;
    public GameObject gameOverScore;
    public GameObject Player;
    public static float scoreAmount;

    public void Start()
    {
        scoreText = GetComponent<Text>();
        scoreAmount = 0.0f;
        PIPS = 1.0f;
    }

    public void Update()
    {
        if (Player.activeInHierarchy == true)
        {
            scoreText.text = scoreAmount.ToString("F0");
            scoreAmount += PIPS * Time.deltaTime;
        }
        else
        {
            scoreText.enabled = false;
            gameOverScore.GetComponent<TextMeshProUGUI>().text = scoreAmount.ToString("F0");
        }
    }
}

虽然这不是理想的方式,但您可以在 Awake 和 OnDisable() 上使用播放器偏好设置。

using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class score : MonoBehaviour
{
private Text scoreText;
private float PIPS;
public GameObject gameOverScore;
public GameObject Player;
public static float scoreAmount;
public float HighScore;

public void Start()
{
    scoreText = GetComponent<Text>();
    scoreAmount = 0.0f;
    PIPS = 1.0f;
}

private void OnDisable()
{
    // this will save the highscore in playerprefs when the game ends[application quit].

    PlayerPrefs.SetFloat("HighScore", HighScore);
}

private void Awake()
{
    // this will load the highscore from playerprefs
    HighScore = PlayerPrefs.GetFloat("HighScore");
}

public void Update()
{
    if (Player.activeInHierarchy == true)
    {
        scoreText.text = scoreAmount.ToString("F0");
        scoreAmount += PIPS * Time.deltaTime;
        if (scoreAmount > HighScore)
        {
            HighScore = scoreAmount;
        }
    }
    else
    {
        scoreText.enabled = false;
        gameOverScore.GetComponent<TextMeshProUGUI>().text = scoreAmount.ToString("F0");
    }
}
}

如果这有帮助,请告诉我。

这是我的一个脚本中的实例 -->

int HighScore = PlayerPerfs.GetInt("HighScore", 0) //If playing First Time Score = 0
void Save()
    {
        if(ScoreUpdate.CurrentScore > HighScore) //Check if CurrentScore is more than HighScore
        {
            PlayerPrefs.SetInt("HighScore", ScoreUpdate.CurrentScore);//Save New High Score
        }
    }

你现在只需要在游戏完成或玩家死亡(如果在任何时候死亡)时调用此函数Save()

编辑:将您的变量替换为 ScoreUpdate