【发布时间】:2020-12-12 14:49:14
【问题描述】:
我正在使用 PlayerPrefs 在我们的游戏中保存 5 个高分。 PlayerPrefs 在使用 Unity 编辑器时工作正常,但是当我在我的 Android 上构建和运行游戏时,分数没有保存。
--更新--
当硬编码(手动设置值)高分时,值会显示在 Android 上。但是,得分并不能与玩家输掉时的得分进行比较。
void Update() {
if (CurrentHealth == 0)
{
Dead();
}
}
void Dead() {
pauseMenuUI.SetActive(true);
Time.timeScale = 0f;
//Check to see if a high score is achieved
scoreManager.checkScore(score.returnScore());
}
检查高分并保存到 PlayerPrefs 的代码
public void checkScore(int score)
{
if(score > PlayerPrefs.GetInt("HighScore1" ))
{
PlayerPrefs.SetInt("HighScore1", score);
PlayerPrefs.Save();
}
else if (score > PlayerPrefs.GetInt("HighScore2"))
{
PlayerPrefs.SetInt("HighScore2", score);
PlayerPrefs.Save();
}
else if (score > PlayerPrefs.GetInt("HighScore3"))
{
PlayerPrefs.SetInt("HighScore3", score);
PlayerPrefs.Save();
}
else if (score > PlayerPrefs.GetInt("HighScore4"))
{
PlayerPrefs.SetInt("HighScore4", score);
PlayerPrefs.Save();
}
else if (score > PlayerPrefs.GetInt("HighScore5"))
{
PlayerPrefs.SetInt("HighScore5", score);
PlayerPrefs.Save();
}
}
编码从 PlayerPrefs 检索高分
private void Awake()
{
instance = this;
highScore1 = PlayerPrefs.GetInt("HighScore1");
highScore2 = PlayerPrefs.GetInt("HighScore2");
highScore3 = PlayerPrefs.GetInt("HighScore3");
highScore4 = PlayerPrefs.GetInt("HighScore4");
highScore5 = PlayerPrefs.GetInt("HighScore5");
createArray();
}
void Start()
{
}
//Creates Initial Array
public void createArray()
{
int[] HighScore = {highScore1, highScore2, highScore3, highScore4, highScore5};
this.HighScore = HighScore;
}
//Allows for the array to be returned
public int[] getArray()
{
createArray();
return this.HighScore;
}
将高分打印到屏幕的代码
public String[] printScores() // Gett array of high scores as string array
{
Highscores = scoreManager.getArray();
String[] scores = new string[Highscores.Length];
for(int i = 0; i < Highscores.Length; i++)
{
text.text = text.text + "Score " + (i+1).ToString() + " " + Highscores[i].ToString() + "\n";
}
return scores;
}
我正在 Galaxy S10+ 上构建和运行游戏。当玩家输掉比赛时,会调用检查高分的代码。打印分数的代码在该场景的 Start() 方法中调用。
【问题讨论】:
-
检查文件是否保存在您的手机上,您可以在 Unity 文档docs.unity3d.com/ScriptReference/PlayerPrefs.html中找到文件的位置@
-
如果它根本不起作用(文件夹不存在),您可能需要编写自己的安全方法并将文件写入 Application.persistantPath。无论如何,高分可能更好,因为您可以加密和解密您的文件,因此操作变得更加困难。
-
MathewHD 所建议的至少在用户进度丢失方面可以节省很多。您应该将重要的值保存到专用文件中
-
@MathewHD 在测试了更多东西之后,我相信比较另一个文件中的分数的方法可能存在问题。当我使用 PlayerPref 代码对脚本中的值进行硬编码时,它会显示在 Android 上。