c# - Unity 2019.4.11f1:PlayerPrefs 未保存在 Android 设备上,但在 Unity 中正确保存
问题描述
我正在使用 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() 方法中调用。
解决方案
密切关注 PlayerPrefs!他们喜欢改变。
开个玩笑,你的电脑和你的手机与 PlayerPrefs 的区别只是第一个值。如果您第一次调用 PlayerPrefs.GetInt,该值将是随机的,它不会从零开始。在您的计算机上,您可能能够第一次设置高分,因此在接下来的尝试中,它总是有效。在手机上,当你第一次玩游戏时,第一个高分可能是负数,所以你的系统其余部分都坏了!
而不是写
PlayerPrefs.GetInt("Higscore");
写
PlayerPrefs.GetInt("Higschore",0);
这样,如果 Unity 第一次没有找到该值,会将其设置为零。你的系统会正常工作
推荐阅读
- ios - 轻按推送通知时 userNotificationCenter 未运行
- ios - UIView 没有像预期的那样模糊
- html - 在 div 中制作 100% 宽度的固定/粘性标题
- spring-boot - 当我想保存值时如何使用@manytoone 在带有角度的弹簧启动中为空
- neo4j - Py2neo (Neo4j) 批量插入/创建关系
- java - 使用 Ant 构建 Java Web 项目时出现 Azure Pipeline 错误
- java - 按降序嵌套for循环 - Java
- actionscript-3 - AS3,动画正确显示,但导致“ArgumentError:错误 #2109:在场景 idleForwards 中找不到帧标签 idleForwards。”
- reactjs - ReactiveSearch 向 elasticsearch 请求添加标头
- kubernetes - EKS 阻止特定外部 IP 查看 nginx 应用程序