PlayerPrefs
PlayerPrefs 是Unity内置的一个静态类,可以用于存储一些简单的数据类型:int ,string ,float。
分别对应的函数为:
SetInt();保存整型数据;
GetInt();读取整形数据;
SetFloat();保存浮点型数据;
GetFlost();读取浮点型数据;
SetString();保存字符串型数据;
GetString();读取字符串型数据;
储存位置
1.在Mac OS X上存储在~/Library/PlayerPrefs文件夹,名为unity.[company name].[product name].plist,这里company和product名是在project Setting中设置的。
2.在windows下,playerPrefs被存储在注册的HKCU\Software[company name][product name]键下,这里company和product名是在project setting中设置的。
3.在Android上,数据存储(持久化)在设备上,数据保存在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("1 " + PlayerPrefs.GetInt("stringIntName"));
PlayerPrefs.SetFloat("stringFloatName", floatValue);
PlayerPrefs.DeleteKey("stringFloatName");
Debug.Log("2 "+PlayerPrefs.GetInt("stringFloatName"));
PlayerPrefs.SetString("stringStringName", stringValue);
PlayerPrefs.DeleteKey("stringStringName");
Debug.Log("3 " + PlayerPrefs.GetInt("stringStringName"));
输出如下
//over