2014-10-26 76 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