我有一个脚本,每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()上使用Playerprefs。
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