Float Variable没有保存到playerprefs How Do I Fix This Unity



所以我试图保存浮动变量cors.Destroyers每次我的玩家与硬币碰撞时,我都会使=1相等,然后我确保当我单击密钥S[/em>时,它应该保存到我的玩家预制件上,但当我出于某种原因重新启动游戏时,它会返回到0尝试修复这个问题有一段时间了,我仍然不确定为什么它根本没有保存,但当我试图使我的变量静态时,它可以工作,但我不希望它是静态变量,我希望它在没有静态变量的情况下工作任何帮助都非常感谢

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityEngine.UI;
using TMPro;
public class savegameprogress2 : MonoBehaviour
{
public COINS cors;
private void Start()
{
LoadGame();
//Debug.Log(COINS.gamecoin);
Debug.Log(cors.Destroyers);
}
void Update()
{

if (Input.GetKeyDown(KeyCode.S))
{
SaveGame();
}
}
public void SaveGame()
{
PlayerPrefs.SetFloat("mainmoney", COINS.gamecoin );
PlayerPrefs.SetFloat("destroy", cors.Destroyers);
PlayerPrefs.Save();
Debug.Log("Game data saved!");
}
void LoadGame()
{
if (PlayerPrefs.HasKey("SavedInteger"))
{
//save for scene 2
COINS.gamecoin = PlayerPrefs.GetFloat("mainmoney");
cors.Destroyers = PlayerPrefs.GetFloat("destroy");
}
else
Debug.LogError("There is no save data!");
}

对代码进行以下调整:

  • 在启动方法中,通过使用HasKey方法。如果它不存在,请指定一个0值
  • 退出游戏前,请确保将首选项保存到磁盘上

代码:

void Start(){
if(!PlayerPrefs.HasKey("mainmoney")){
PlayerPrefs.SetFloat("mainmoney", 0);
}
if(!PlayerPrefs.HasKey("destroy")){
PlayerPrefs.SetFloat("destroy", 0);
}
}
void OnApplicationQuit(){
PlayerPrefs.Save;
}

如前所述,我从未见过您使用键SavedIntegerPlayerPrefs中设置任何内容!

所以,要么你没有和我们分享一个重要的细节,而这实际上是在其他地方发生的。。。否则它将永远不存在。


您可能想要这样做,例如

public void SaveGame()
{
PlayerPrefs.SetFloat("mainmoney", COINS.gamecoin );
PlayerPrefs.SetFloat("destroy", cors.Destroyers);
// The actual type and value doesn't matter since you only check for the existence of the key
PlayerPRefs.SetInt("SavedInteger", 1);
PlayerPrefs.Save();
Debug.Log("Game data saved!");
}

或者,您已经拥有至少两个可以/应该检查的其他密钥,而不是引入一个新密钥。你可以简单地检查

if(PlayerPrefs.HasKey("mainmoney"))

一般注意:您应该为键引入一些const字段,而不是到处都有硬编码的string值。它可以防止拼写错误,并使以后在一个中心点中更容易地重命名密钥

private const string MAINMONEY = "mainmoney";
private const string DESTROY = "destroy";

然后起诉

PlayerPrefs.SetFloat(MAINMONEY, COINS.gamecoin );
PlayerPrefs.SetFloat(DESTROY, cors.Destroyers);

if(PlayerPrefs.HasKey(MAINMONEY))
{
COINS.gamecoin = PlayerPrefs.GetFloat(MAINMONEY);
cors.Destroyers = PlayerPrefs.GetFloat(DESTROY);
...

最新更新