【问题标题】:having trouble in increasing value of prefab by PlayerPrefs Unity无法通过 PlayerPrefs Unity 增加预制件的价值
【发布时间】:2019-11-28 22:53:27
【问题描述】:

我正在尝试在加载到下一个场景时增加预制件的值(当游戏开始时预制件正在实例化),但我在使用 playerprefs 加载增量值时遇到问题。

这是我在GunScript.cs 中设置播放器首选项值的地方

GunScript.cs

void Awake() {
  PlayerPrefs.SetFloat("Inaccuracy", inaccuracy);
  Debug.Log(PlayerPrefs.GetFloat("Inaccuracy"));
}

每当我点击下一个按钮时,都会加载相同的场景,我希望在 LevelLoad.cs 脚本中将这个不准确值增加 2。

LevelLoad.cs

public void OnNext(){
    PlayerPrefs.SetFloat("Inaccuracy", 
    PlayerPrefs.GetFloat("Inaccuracy") + 2);
    print(PlayerPrefs.GetFloat("Inaccuracy"));
    SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}

它正在打印增量值,但prefab 中没有增加值。

【问题讨论】:

  • 你绝对不应该将 PlayerPrefs 用于那种东西,它并不意味着在运行时不断更新。你为什么不使用单例、静态变量或其他的东西?
  • 此行无效:PlayerPrefs.GetFloat("Inaccuracy") + 2); 您只有一个(,但有两个)

标签: unity3d


【解决方案1】:

我推荐这种方法,它将值存储到临时变量中,执行计算,然后更新播放器首选项。

public void OnNext()
{
   float previousValue = PlayerPrefs.GetFloat("Inaccuracy", 0); //0 is the default
   float newValue = previousValue + 2f;

   PlayerPrefs.SetFloat("Inaccuracy", newValue);
   print(PlayerPrefs.GetFloat("Inaccuracy"));    

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 2011-08-11
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多