【Unity入门】PlayerPrefs简介及使用

PlayerPrefs

PlayerPrefs 是Unity内置的一个静态类,可以用于存储一些简单的数据类型:int ,string ,float。
分别对应的函数为:

  • SetInt():保存整型数据
  • GetInt():读取整形数据
  • SetFloat():保存浮点型数据
  • GetFlost():读取浮点型数据
  • SetString():保存字符串型数据
  • GetString():读取字符串型数据

其它函数

  • DeleteAll():删除所有键和值,请谨慎使用。
  • DeleteKey():从PlayerPrefs中删除给定的key。如果key不存在,DeleteKey就没有影响。
  • HasKey():如果给定key存在于PlayerPrefs中,则返回true,否则返回false。
  • Save():将所有修改的偏好写入磁盘。

储存位置

保存在 PlayerPrefs 上的数据存储于设备本地。

  • 在Mac OS X上,PlayerPrefs数据存储在~/Library/PlayerPrefs文件夹,名为unity.[company name].[product name].plist,这里company和product名是在project Setting中设置的。
  • 在windows上,PlayerPrefs数据存储在注册的HKCU\Software[company name][product name]键下,这里company和product名是在project setting中设置的。
  • 在Android上,PlayerPrefs数据存储(持久化)在设备上,数据保存在SharedPreferences中。

用例

int intValue = 0;
float floatValue = 0f;
string stringValue = " ";

//三个数据类型的存储和调用
PlayerPrefs.SetInt("stringIntName", intValue);
PlayerPrefs.GetInt("stringIntName");

PlayerPrefs.SetFloat("stringFloatName", floatValue);
PlayerPrefs.GetFloat("stringFloatName");

PlayerPrefs.SetString("stringStringName", stringValue);
PlayerPrefs.GetString("stringStringName");

PlayerPrefs.HasKey("stringIntName");//返回 true
PlayerPrefs.DeleteKey("stringIntName");//删除"stringIntName"键值对
PlayerPrefs.HasKey("stringIntName");//返回 false
PlayerPrefs.DeleteAll();//删除所有数据

注意事项

用DeleteKey方法删除某个数据后再用HasKey判断是否存在,会返回false,但是用Get方法去得到一个不存在的值,会返回0。

int intValue = 5;
float floatValue = 5f;
string stringValue = "aaaa";

PlayerPrefs.SetInt("stringIntName", intValue);
PlayerPrefs.DeleteKey("stringIntName");
Debug.Log("stringIntName: " + PlayerPrefs.GetInt("stringIntName"));

PlayerPrefs.SetFloat("stringFloatName", floatValue);
PlayerPrefs.DeleteKey("stringFloatName");
Debug.Log("stringFloatName: "+PlayerPrefs.GetInt("stringFloatName"));

PlayerPrefs.SetString("stringStringName", stringValue);
PlayerPrefs.DeleteKey("stringStringName");
Debug.Log("stringStringName: " + PlayerPrefs.GetInt("stringStringName"));

控制台
在这里插入图片描述

如果Get方法去得到一个不存在的值,可设置默认值进行返回

PlayerPrefs.GetInt("stringIntName",1);

PlayerPrefs.GetFloat("stringFloatName",2f);

PlayerPrefs.GetString("stringStringName","hello");

关于 PlayerPrefs 类的用法更多详情

猜你喜欢

转载自blog.csdn.net/weixin_45961836/article/details/135212130