2014-10-26 85 views
1

我想在游戏中保存高分。高分在比赛中用得分更新。但是,级别重新启动后,(当前分数和高分)变为零。如何保存高分?

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

这里是我的代码:

生成

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

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

if (score > highScore)

因为你设置highScore = 0同时宣布变量,score总是更大。

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

private int highScore; 

Start()如果存在的话,你应该给它救了高分的值,如果没有,给它0值:

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

这应该适合你。

1

这条线开始(),实际上不会做任何事情。

PlayerPrefs.GetInt ("highscore", newhighScore); 

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

我想你的意思做的是:

newhighScore = PlayerPrefs.GetInt("highscore"); 

的默认值是0,没有明确设置时。

+0

感谢人...没有人出现问题,那就是当我停止游戏,然后根据最近在前一游戏退出后打开的新游戏来玩游戏高分组时。例如当我得分7并且保存为高分7.但是在游戏退出并且然后重新开始游戏并且得分为2时,高分从7变为2。 – user3866627 2014-10-26 19:48:48