如何保存高分

本文关键字:保存 何保存 | 更新日期: 2023-09-27 18:28:03

我正在努力挽救比赛中的高分。在游戏过程中,高分会随着分数而更新。但是,在级别重新启动后,两者(当前分数和高分)都变为零。

我该怎么做?我犯了什么错误?

这是我的代码:

生成

public class Generate : MonoBehaviour 
{    
    private static int score;
    public GameObject birds;
    private string Textscore;
    public GUIText TextObject;
    private int highScore = 0;
    private int newhighScore;
    private string highscorestring;
    public GUIText highstringgui;
    // Use this for initialization
    void Start()
    {
        PlayerPrefs.GetInt ("highscore", newhighScore);
        highscorestring= "High Score: " + newhighScore.ToString();
        highstringgui.text = (highscorestring);
        InvokeRepeating("CreateObstacle", 1f, 3f);
    }
    void Update()
    {
        score = Bird.playerScore; 
        Textscore = "Score: " + score.ToString();
        TextObject.text = (Textscore);
        if (score > highScore) 
        {
            newhighScore=score;
            PlayerPrefs.SetInt ("highscore", newhighScore);
            highscorestring = "High Score: " + newhighScore.ToString ();
            highstringgui.text = (highscorestring);
        } 
        else 
        {
            PlayerPrefs.SetInt("highscore",highScore);
            highscorestring="High Score: " + highScore.ToString();
            highstringgui.text= (highscorestring);
        }
    }
    void CreateObstacle()
    {
        Instantiate(birds);
    }
} 

public class Bird : MonoBehaviour {
    public GameObject deathparticales;
    public Vector2 velocity = new Vector2(-10, 0);
    public float range = 5;
    public static int playerScore = 0;
    // Use this for initialization
    void Start()
    {    
        rigidbody2D.velocity = velocity;
        transform.position = new Vector3(transform.position.x, transform.position.y - range * Random.value, transform.position.z);      
    }
    // Update is called once per frame
    void Update () { 
        Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
        if (screenPosition.x < -10)
        {
            Die();
        }
    }    
    // Die by collision
    void OnCollisionEnter2D(Collision2D death)
    {
            if(death.transform.tag == "Playercollision")
        {
            playerScore++;
            Destroy(gameObject);
            Instantiate(deathparticales,transform.position,Quaternion.identity);
        }
    }
    void Die()
    {
        playerScore =0;
        Application.LoadLevel(Application.loadedLevel);    
    }
}

如何保存高分

问题是您的变量highScore。它总是0。在游戏中你问

if (score > highScore)

因为在声明该变量时设置了highScore = 0,所以score总是更大。

我的建议是,你应该声明它没有价值:

private int highScore;

Start()中,如果它存在,你应该给它保存高分的值,如果它不存在,给它0值:

highScore = PlayerPrefs.GetInt("highscore", 0);

这应该对你有用。

Start()中的这一行实际上不会做任何事情。

PlayerPrefs.GetInt ("highscore", newhighScore);

如果给定的键不存在,第二个参数是默认的返回值。但是您没有将返回值用于任何内容。

我想你想做的是:

newhighScore = PlayerPrefs.GetInt("highscore");

如果未明确设置,则默认值为0。