Unity中PlayerPrefs类的用法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44927626/article/details/95339886

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

猜你喜欢

转载自blog.csdn.net/weixin_44927626/article/details/95339886