Unity 2D:高分的PlayerPrefs实现

时间:2018-02-11 14:00:30

标签: unity3d unity5 unityscript unity3d-2dtools

我需要一些实施保存的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");

    }
}

1 个答案:

答案 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;
    }
}

关于代码的情结说明:

  • 永远不要使用所谓的&#34;魔术数字&#34;在脚本中,如果那些变量是不可变的,可以利用const变量。
  • 我添加了gameOver的使用,因为您将其声明为private,并且它未在课程中的任何位置使用过。这将在分数设置为true时停止计分。
  • 将分数类型更改为int,这样更合适。