Playerprefs添加Ints

时间:2017-02-09 01:45:42

标签: c# unity3d

所以我知道PlayerPrefs.SetInt("counter", 1);,但我正在尝试制作一个计数器,并保存计数器分数。没有PlayerPrefs.AddInt("Counter", 1);而且有点卡住了。

1 个答案:

答案 0 :(得分:0)

没有AddInt之类的东西。您必须使用int阅读旧PlayerPrefs.GetInt,将1读取的数据增加,然后使用PlayerPrefs.SetInt将其保存回来。

每次增加时都不应保存值。在游戏过程中增加,但保存,当您即将退出游戏或进入下一个场景时。这将确保在游戏过程中不断读取和写入数据不会影响性能。

如果你仍然坚持这样做,那么这里有一个Helper类可以做到这一点:

namespace EXT
{
    public class PlayerPrefs
    {
        public static void AddInt(string key, int numberToAdd)
        {
            //Check if the key exist
            if (UnityEngine.PlayerPrefs.HasKey(key))
            {
                //Read old value
                int value = UnityEngine.PlayerPrefs.GetInt(key);

                //Increment
                value += numberToAdd;

                //Save it back
                UnityEngine.PlayerPrefs.SetInt(key, value);
            }
        }

        public static void SubstractInt(string key, int numberToSubstract)
        {
            //Check if the key exist
            if (UnityEngine.PlayerPrefs.HasKey(key))
            {
                //Read old value
                int value = UnityEngine.PlayerPrefs.GetInt(key);

                //De-Increment
                value -= numberToSubstract;

                //Save it back
                UnityEngine.PlayerPrefs.SetInt(key, value);
            }
        }
    }
}

<强>用法

//Add one
EXT.PlayerPrefs.AddInt("Counter", 1);
//Substract one
EXT.PlayerPrefs.SubstractInt("Counter", 1);