数据持久化 1 - PlayerPrefs

数据持久化

文章目录

PlayerPrefs 基本方法

  • PlayerPrefs Unity用于存储读取玩家数据的公共类

存储

PlayerPrefs的数据存储类似于键值对存储

提供了3种方法 int float string

c 复制代码
PlayerPrefs.SetInt("myInt", 1);
PlayerPrefs.SetString("myString", "str");
PlayerPrefs.SetFloat("myFloat", 10.1f);

// set方法只会把数据存储到内存中
// 游戏结束运行时回存入硬盘中,所以游戏非正常结束时会丢失数据
PlayerPrefs.Save(); // 调用Save方法存储到硬盘中

读取

c 复制代码
// 不存在时返回默认值
int myInt = PlayerPrefs.GetInt("myInt");
int myInt2 = PlayerPrefs.GetInt("myInt", 100); // 参数:(key, 找不到将会返回的默认值)
// 判断是否存在
bool f = PlayerPrefs.HasKey("myInt");

删除

c 复制代码
PlayerPrefs.DeleteKey("myInt");
PlayerPrefs.DeleteAll(); // 删除所有

Type补充

父子关系

c 复制代码
// 判断某个类型是否能为自己分配空间(即父类)
Type fatherType = typeof(Father); // 获得父类Type
Type sonType = typeof(Son); // 获得子类Type
if (fatherType.IsAssignableFrom(sonType)) 	
{
    print("yes");    
}

通过反射获得泛型类型

c 复制代码
List<string, int> list = new List<string, int>();
// 获得Type
Type typeList = list.GetType();
Type[] types = typeList.GetGenericArguments(); // 获得泛型类型,返回值是type数组(泛型类型可能不止一个)
相关推荐
沫璃染墨2 小时前
从零入门数据结构与算法(一):复杂度分析——从算法效率到时间与空间复杂度
c语言·开发语言·数据结构·笔记·算法·飞书
字节暗面4 小时前
客户端上报不可信:游戏服务端数据校验与对局重演设计
c#·游戏开发·服务端校验·反作弊
chingho4 小时前
GitHub上这10个C#项目,不仅实用,还怪好玩的
c#·github·.net·开源项目
心仪久了会沦陷5 小时前
C语言数据结构入门——队列补充:循环队列的数组实现
c语言·开发语言·数据结构·笔记
careathers6 小时前
【数据结构】二叉树拓展
数据结构·算法
半亩码田6 小时前
C#转Python第5.1篇:异步编程:asyncio vs async/await,语法相似但机制不同
开发语言·python·c#
m0_547486666 小时前
《数据结构:基于C语言的描述》全套PPT课件2026
c语言·数据结构
阿华田5127 小时前
Java 类加载冲突实战:解决 is not an instance of
c#·linq
垆边人似月.7 小时前
华为题:最多可以参加的会议数目
数据结构·c++·算法
Tongzhi20267 小时前
2026 年考勤行业趋势:考勤正在从“打卡工具“变成“人力成本中枢“
大数据·数据结构·数据仓库·科技·数据库开发