Unity提供了一个用于本地持久化保存与读取数据的类——PlayerPrefs。
工作原理:以键值对的形式将数据保存在本地注册表 regedit(HKEY_CURRENT_USER——SoftWare——Unity)中。
保存数据:
SetFloat():保存浮点类型
SetInt():保存整型
SetString():保存字符串
3.获取数据:
GetFloat():获取浮点类型
GetInt():获取整型
GetString():获取字符串
4.删除数据:
DeleteAll():将所有键对应的值数据都删除
DeleteKey():删除某一项数据,其参数为所删除数据的名称
HasKey():判断是否存有这项数据,其参数为判断的数据名称
5.脚本示例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerfrsTest : MonoBehaviour
{
string name = "张三";
string passWord = "888888";
//写入数据
public void SetInfo()
{
//第一个参数是存储数据的名称,第二个参数表示具体存储的值
PlayerPrefs.SetString("name", name);
PlayerPrefs.SetString("pass", passWord);
PlayerPrefs.SetInt("num", 100);
PlayerPrefs.SetFloat("pai", 3.14f);
}
//读取数据
public void GetInfo()
{
//读取数据时,如果没有找到对应名称存储的数据,可以在方法中增加返回默认值的参数,如GetString("name",张三),当没有找到name所存储的数据,则默认返回张三
string na = PlayerPrefs.GetString("name");
string pa = PlayerPrefs.GetString("pass");
int number = PlayerPrefs.GetInt("num");
float f = PlayerPrefs.GetFloat("pai");
print(na + " " + pa + " " + number + " " + f);
}
//删除写入注册表中的所有数据
public void DeKey()
{
PlayerPrefs.DeleteAll();
}
}
6.缺点:不适合处理大量的数据,想要存储大量数据可以使用本地文本文件、json、xml或数据库等