如何保存高分?

时间:2014-10-26 18:44:01

标签: c# unity3d unityscript

我正试图在游戏中保存高分。在比赛期间用分数更新高分。但是,在等级重启后,(当前得分和高分)都变为零。

我该怎么做?我在做什么错误?

这是我的代码:

生成

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);    
    }
}

2 个答案:

答案 0 :(得分:2)

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

if (score > highScore)

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

我的建议是你应该宣布它没有价值:

private int highScore;

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

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

那应该适合你。

答案 1 :(得分:1)

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

PlayerPrefs.GetInt ("highscore", newhighScore);

如果给定的键不存在,则第二个参数是默认返回值。 但你没有使用返回值。

我认为你的意思是:

newhighScore = PlayerPrefs.GetInt("highscore");

未明确设置时,默认值为0。