我正试图在游戏中保存高分。在比赛期间用分数更新高分。但是,在等级重启后,(当前得分和高分)都变为零。
我该怎么做?我在做什么错误?
这是我的代码:
生成
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);
}
}
答案 0 :(得分:2)
问题是你的变量highScore。它总是0
。在你要求的游戏中
if (score > highScore)
因为您在声明该变量时设置highScore = 0
,score
总是更大。
我的建议是你应该宣布它没有价值:
private int highScore;
在Start()
中,如果存在,则应该将保存的高分值赋予它,如果不存在,则给它0
值:
highScore = PlayerPrefs.GetInt("highscore", 0);
那应该适合你。
答案 1 :(得分:1)
Start()中的这一行实际上不会做任何事情。
PlayerPrefs.GetInt ("highscore", newhighScore);
如果给定的键不存在,则第二个参数是默认返回值。 但你没有使用返回值。
我认为你的意思是:
newhighScore = PlayerPrefs.GetInt("highscore");
未明确设置时,默认值为0。