对于游戏存档除了XML,Json,Sqlite,unity提供了一个类可以用来存储数据,那就是PlayerPrefs。
这个类对应的API如下
Class Functions类函数
-
Sets the value of the preference identified by key.
设置由key确定的参数值。 -
Returns the value corresponding to key in the preference file if it exists.
如果存在,返回偏好文件中key对应的值。 -
Sets the value of the preference identified by key.
设置由key确定的参数值。 -
Returns the value corresponding to key in the preference file if it exists.
如果存在,返回游戏存档文件中key对应的值。 -
Sets the value of the preference identified by key.
设置由key确定的参数值。 -
Returns the value corresponding to key in the preference file if it exists.
如果存在,返回游戏存档文件中key对应的值。 -
Returns true if key exists in the preferences.
如果key在游戏存档中存在,返回true。 -
Removes key and its corresponding value from the preferences.
从游戏存档中删除key和它对应的值。
-
Removes all keys and values from the preferences. Use with caution.
从偏好中删除所有key。请谨慎使用。 -
Writes all modified preferences to disk.
写入所有修改参数到硬盘。
1.存储的数据类型只支持int,float,string三种类型。
2.在unity中该类是使用键值对存储数据的。
3.当通过键名来读取值得时候,如果对应的值不存在,就返回默认值。
4.基本用法:
PlayerPrefs.SetString("Name",mName);
PlayerPrefs.SetInt("Age",mAge);
PlayerPrefs.SetFloat("Grade",mGrade)
PlayerPrefs.SetString("Name",mName);
PlayerPrefs.SetInt("Age",mAge);
PlayerPrefs.SetFloat("Grade",mGrade)
下面用一个实例来说明具体的用法:
public class Playerprefs : MonoBehaviour
{
public string set_NAME;
public string get_NAME;
void OnGUI()
{
GUILayout.BeginHorizontal("box");
GUILayout.Label("姓名:");
set_NAME = GUILayout.TextArea(set_NAME, 200, GUILayout.Width(50));
if (GUILayout.Button("存储数据"))
{
//将我们输入的姓名保存到本地,命名为_NAME ;
PlayerPrefs.SetString("_NAME", set_NAME);
}
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal("box");
if (GUILayout.Button("读取数据"))
{
//读取本地数据中名称为_NAME 的数据;
get_NAME = PlayerPrefs.GetString("_NAME");
}
GUILayout.Label("你输入的姓名:" + get_NAME);
GUILayout.EndHorizontal();
}
}