简体   繁体   English

为什么这些值未添加到PlayerPrefs文件中?

[英]Why are the values not being added to the PlayerPrefs file?

I am trying to save values to files in the PlayerPrefs for my mobile game in Unity however, the files do not update after playing the game. 我试图将值保存到Unity中移动游戏的PlayerPrefs文件中,但是,玩游戏后文件不会更新。

public class gameManager : MonoBehaviour {

    private static gameManager instance;
    public static gameManager Instance { get { return instance; } }

    public int currentSkinIndex;
    public int currency  = 0;
    public int skinAvailability = 0;

    private void Awake()
    {
        instance = this;
        DontDestroyOnLoad (gameObject);

        if (PlayerPrefs.HasKey ("currency")) {
            // We had a previous session
            currentSkinIndex = PlayerPrefs.GetInt ("currentSkinIndex");
            currency = PlayerPrefs.GetInt ("currency");
            skinAvailability = PlayerPrefs.GetInt ("skinAvailability");
        } else {
            Save ();
        }
    }

    public void Save ()
    {
        PlayerPrefs.SetInt ("currentSkin", 0);
        PlayerPrefs.SetInt ("currency", 0);
        PlayerPrefs.SetInt ("skinAvailability", 1);
    }
}

I think the logic that you wrote has a problem! 我认为您编写的逻辑有问题! In Awake() you have two conditions => if there is key and if the is not! Awake()您有两个条件=>如果有密钥,如果没有密钥!

You want to save some values to playerprefs and you have the save function already, but in Awake() you just call it under two conditions, here is what your code says: 您想将一些值保存到playerprefs,并且已经具有保存功能,但是在Awake()您只需要在两个条件下调用它,这就是您的代码所说的:

  1. Search through existing player prefs if the values exist, retrieve them 搜索现有的播放器偏好设置(如果存在),然后检索它们
  2. Or if they don't exist, then save them as I order to you to save them (inside save function logic => currency = 0 , current skin = 0, skinAvailability = 1 ) 或者,如果它们不存在currency = 0 , current skin = 0, skinAvailability = 1我的命令保存它们(保存功能逻辑=> currency = 0 , current skin = 0, skinAvailability = 1
  3. Then do nothing. 然后什么都不做。 Keep in mind that all of this happens during Awake() 请记住,所有这些都是在Awake()期间发生的

But the new values that you get after playing the game need to be saved too! 但是玩游戏后获得的新价值也需要保存! And you don't save them! 而且您不保存它们!

Your code does not say to "after I played the game (and the variables have changed), save the values again. " 您的代码不会说“我玩完游戏(变量已更改)后, 再次保存值

You need to save them again! 您需要再次保存! For example you can do that when exiting the play scene by writing a function or if you already written that function, you can assign it to a button which is been called savebtn which calls that function when clicked. 例如,您可以通过编写一个函数退出播放场景,或者如果您已经编写了该函数,则可以将其分配给一个名为savebtn的按钮,单击该按钮即会调用该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM