我需要一些实施保存的HighScore的帮助。目前,我有一个分数,从500,000开始,每秒下降150点。这是有效的,虽然当我死了它仍然继续,我需要修复。我有第二个kmHighscore Text,我想让它显示高分。现在它显示了我死亡的确切分数(例如450,875),但是当我重新开始游戏时,我似乎无法将其保存。我尝试使用PlayerPrefs,但我不确定如何在我的代码中应用它。我希望它代表最低,在这种情况下,因为它从500,000开始,得分。需要注意的是:kmScore和kmHighscore都只是数字,我在Unity窗口中没有得分或高分的文字。任何帮助将不胜感激!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameOver : MonoBehaviour {
public GameObject gameOverScreen;
public Text kmScore;
public Text kmHighscore;
float savedScore;
bool gameOver;
private float score = 500000;
void Start () {
FindObjectOfType<PlayerController>().OnPlayerDeath += OnGameOver;
}
public void Update () {
kmScore.text = GetScore().ToString("F0");
if (gameOver)
{
if (Input.GetKeyDown (KeyCode.Space))
{
SceneManager.LoadScene(1);
}
}
}
float GetScore()
{
return score - (float)Time.timeSinceLevelLoad * 150;
}
void OnGameOver()
{
gameOverScreen.SetActive (true);
kmHighscore.text = GetScore().ToString("F0");
}
}
答案 0 :(得分:2)
您应该将脚本更改为:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameOver : MonoBehaviour {
const string PLAYERPREFS_HIGHSCORE = "High Score";
const int STARTING_SCORE = 500000, POINTS_PER_SECOND = 150;
public GameObject gameOverScreen;
public Text kmScore, kmHighscore;
private int allTimeHighScore, actualScore;
private bool gameOver;
private void Start() {
allTimeHighScore = PlayerPrefs.GetInt(PLAYERPREFS_HIGHSCORE, STARTING_SCORE);
gameOver = false;
FindObjectOfType<PlayerController>().OnPlayerDeath += OnGameOver;
kmHighscore.text = allTimeHighScore.ToString("F0");
}
private void Update() {
if (gameOver) {
if (Input.GetKeyDown(KeyCode.Space)) {
SceneManager.LoadScene(1);
}
}
else {
kmScore.text = GetScore().ToString("F0");
}
}
private int GetScore() {
return actualScore = STARTING_SCORE - (int)Time.timeSinceLevelLoad * POINTS_PER_SECOND;
}
private void OnGameOver() {
gameOverScreen.SetActive(true);
if (allTimeHighScore > GetScore()) {
kmHighscore.text = (allTimeHighScore = actualScore).ToString("F0");
PlayerPrefs.SetInt(PLAYERPREFS_HIGHSCORE, allTimeHighScore);
}
gameOver = true;
}
}
关于代码的情结说明:
const
变量。gameOver
的使用,因为您将其声明为private
,并且它未在课程中的任何位置使用过。这将在分数设置为true
时停止计分。int
,这样更合适。