【发布时间】:2017-05-24 01:34:07
【问题描述】:
我有一个没完没了的游戏,分数根据 Time.fixedDeltaTime 增加。如果它高于获得的分数,我会尝试在玩家偏好中存储高分,但它似乎并没有坚持下去。有人可以指出我在这里做错了什么吗?我使用 HUDScript 将分数存储在 PlayerPrefs 中,并使用 GameOverScript 在游戏结束场景中呈现分数和高分。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HUDScript : MonoBehaviour {
float playerScore = 0;
public Text scoreText;
float highScore;
public Text highScoreText;
void Start () {
highScore = PlayerPrefs.GetFloat ("Highscore", 0);
}
void Update () {
playerScore += Time.fixedDeltaTime;
scoreText.text = "Score: " + Mathf.Round((playerScore * 100)).ToString();
if (playerScore > highScore) {
highScore = playerScore;
PlayerPrefs.SetFloat ("Highscore", Mathf.Round (highScore * 100));
PlayerPrefs.Save ();
}
}
public void IncreaseScore(int amount){
playerScore += amount;
}
void OnDisable() {
PlayerPrefs.SetFloat ("Score", Mathf.Round((playerScore * 100)));
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameOverScript : MonoBehaviour {
HUDScript hud;
float score = 0;
float highScore;
public Text scoreText;
public Text highScoreText;
// Use this for initialization
void Start () {
score = PlayerPrefs.GetFloat ("Score");
scoreText.text = "Score: " + score.ToString ();
highScore = PlayerPrefs.GetFloat ("Highscore");
highScoreText.text = "High Score: " + highScore.ToString ();
PlayerPrefs.Save ();
}
}
【问题讨论】:
-
只是一个建议,应该删除
HUDScript.Update中的保存代码。 HUDScript 什么时候会被禁用? -
到底是什么问题?是不是因为 GameOver 的高分是上一场比赛的高分,而不是最近的?我想帮忙,但您的问题不清楚。
-
对不起,我的问题并不完全清楚。我的确切问题是当游戏重新启动时存储在 PlayerPrefs 中的高分不粘。我正在尝试显示本地持续的高分。现在如果你重新开始游戏,每次玩的分数和高分都是一样的。