您的位置:首页 > 移动开发 > Unity3D

Unity3d中的PlayerPrefs游戏存档API的扩展

2017-04-13 08:50 411 查看

功能

在游戏会话中储存和访问游戏存档。这个是持久化数据储存,比如保存游戏记录。

静态函数

DeleteAll

Removes all keys and values from the preferences. Use with caution. 从游戏存档中删除所有key。请谨慎使用。

DeleteKey

Removes key and its corresponding value from the preferences. 从游戏存档中删除key和它对应的值。

GetFloat

Returns the value corresponding to key in the preference file if it exists. 如果存在,返回游戏存档文件中key对应的浮点数值。

GetInt

Returns the value corresponding to key in the preference file if it exists. 如果存在,返回游戏存档文件中key对应的整数值。

GetString

Returns the value corresponding to key in the preference file if it exists. 如果存在,返回游戏存档文件中key对应的字符串值。

HasKey

Returns true if key exists in the preferences. 如果key在游戏存档中存在,返回true。

Save

Writes all modified preferences to disk. 写入所有修改参数到硬盘。

SetFloat

Sets the value of the preference identified by key. 设置由key确定的浮点数值。

SetInt

Sets the value of the preference identified by key. 设置由key键确定的整数值。

SetString

Sets the value of the preference identified by key. 设置由key确定的字符串值。

代码:

保存数据

PlayerPrefs.SetString("Name",mName);
PlayerPrefs.SetInt("Age",mAge);
PlayerPrefs.SetFloat("Grade",mGrade)


读取数据

mName=PlayerPrefs.GetString("Name","DefaultValue");
mAge=PlayerPrefs.GetInt("Age",0);
mGrade=PlayerPrefs.GetFloat("Grade",0F);


PlayerPrefs的存储是有局限的,在unty3D中只支持int,string,float三种数据类型的写和读。



扩展

由于vector3是Unity3d中非常常见的数据类型,因此在这里我举例把vector3类型扩展到PlayerPrefs里面.

/// <summary>
/// 存储Vector3类型的值
/// </summary>
public static bool SetVector3(string key, Vector3 vector)
{
return SetFloatArray(key, new float[3] { vector.x, vector.y, vector.z });
}

/// <summary>
/// 读取Vector3类型的值
/// </summary>
public static Vector3 GetVector3(string key)
{
float[] floatArray = GetFloatArray(key);
if (floatArray.Length < 3)
return Vector3.zero;
return new Vector3(floatArray[0], floatArray[1], floatArray[2]);
}

把上面的代码放到playerprefs原来的代码里面,就能保存和读取Vector3类型的数据了,其他类型的扩展类似,就不贴代码了.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: