Unity数据持久化之PlayerPrefs高级封装--实现:自定义类型、List<T>、Dictionary<Key,Value>、int、float、string、bool的封装,并对数据进行加密

这篇博客介绍了Unity中PlayerPrefs的局限性,它只能存储基本数据类型,并且数据不安全。作者通过C#的反射机制实现了一个PlayerPrefsMrg管理类,能够存储包括自定义类型、List和Dictionary在内的复杂数据。该类使用单例模式,提供SaveData和LoadData方法,实现了数据的保存和读取。博客还展示了如何使用这个管理类进行测试,确保数据的正确存取。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

PlayerPrefs只能存储三种简单类型的数据,数据非常不安全,并且可以通过资源管理文件进行修改。

修改路径如下:
Windows : HKCU\Software[公司名称][产品名称] 向下的注册表中( 其中公司名称和产品名称是 在”Project Setting”中设置的名称)。
硬盘查找步骤:
运行 regedit
HKCU_CURRENT_USER
SOFTWARE
Unity
UnityEidtor
公司名称
产品名称

Android: /data/data/包名/shared_prefs/pkg-name.xml

IOS:/Library/Preferences/[应用ID].Plist

如果想要存储下面的自定义的数据类型,PlayerPrefs非常难以实现,并且PlayerInfo中含有另一种自定义类型(ItemInfo)。

public class PlayerInfo
{
   
   
    public int age = 10;
    public string name = "未命名";
    public float height = 177.5f;
    public bool sex = true;
    public List<int> list = new List<int>() {
   
    1, 2, 3, 4 };
    public Dictionary<string, int> dic = new Dictionary<string, int>() {
   
    {
   
    "11", 1 }, {
   
    "22", 2 } };
    public ItemInfo itemInfo = new ItemInfo();
    public List<ItemInfo> itemList = new List<ItemInfo>() {
   
    new ItemInfo(1, 10), new ItemInfo(2, 20) };
    public Dictionary<int, ItemInfo> itemDic = new Dictionary<int, ItemInfo>() {
   
    {
   
    3, new ItemInfo(3, 30) }, {
   
    4, new ItemInfo(4, 40) } };
}

public class ItemInfo
{
   
   
    public int id;
    public int num;
    public ItemInfo()
    {
   
   
    }
    public ItemInfo(int id, int num)
    {
   
   
        this.id = id;
        this.num = num;
    }
}

我利用C#的反射机制以及递归思想,实现了可以存储自定类型(里面可以嵌套其它的自定义类型,List,Dictionary<Key,Value>等常用容器)的PlayerPrefs管理类。



开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值