我想在遊戲中保存高分。高分在比賽中用得分更新。但是,級別重新啓動後,(當前分數和高分)變爲零。如何保存高分?
我該怎麼做?我在做什麼錯誤?
這裏是我的代碼:
生成
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);
}
}
感謝人...沒有人出現問題,那就是當我停止遊戲,然後根據最近在前一遊戲退出後打開的新遊戲來玩遊戲高分組時。例如當我得分7並且保存爲高分7.但是在遊戲退出並且然後重新開始遊戲並且得分爲2時,高分從7變爲2。 – user3866627 2014-10-26 19:48:48