功能
在游戲會(huì)話(huà)中儲(chǔ)存和訪問(wèn)游戲存檔。這個(gè)是持久化數(shù)據(jù)儲(chǔ)存,比如保存游戲記錄。
靜態(tài)函數(shù)
DeleteAll
Removes all keys and values from the preferences. Use with caution. 從游戲存檔中刪除所有key。請(qǐng)謹(jǐn)慎使用。DeleteKey
Removes key and its corresponding value from the preferences. 從游戲存檔中刪除key和它對(duì)應(yīng)的值。GetFloat
Returns the value corresponding to key in the preference file if it exists. 如果存在,返回游戲存檔文件中key對(duì)應(yīng)的浮點(diǎn)數(shù)值。GetInt
Returns the value corresponding to key in the preference file if it exists. 如果存在,返回游戲存檔文件中key對(duì)應(yīng)的整數(shù)值。GetString
Returns the value corresponding to key in the preference file if it exists. 如果存在,返回游戲存檔文件中key對(duì)應(yīng)的字符串值。HasKey
Returns true if key exists in the preferences. 如果key在游戲存檔中存在,返回true。Save
Writes all modified preferences to disk. 寫(xiě)入所有修改參數(shù)到硬盤(pán)。SetFloat
Sets the value of the preference identified by key. 設(shè)置由key確定的浮點(diǎn)數(shù)值。SetInt
Sets the value of the preference identified by key. 設(shè)置由key鍵確定的整數(shù)值。SetString
Sets the value of the preference identified by key. 設(shè)置由key確定的字符串值。
代碼:
- 保存數(shù)據(jù)
PlayerPrefs.SetString("Name",mName);
PlayerPrefs.SetInt("Age",mAge);
PlayerPrefs.SetFloat("Grade",mGrade)
- 讀取數(shù)據(jù)
mName=PlayerPrefs.GetString("Name","DefaultValue");
mAge=PlayerPrefs.GetInt("Age",0);
mGrade=PlayerPrefs.GetFloat("Grade",0F);
PlayerPrefs的存儲(chǔ)是有局限的,在unty3D中只支持int,string,float三種數(shù)據(jù)類(lèi)型的寫(xiě)和讀。
擴(kuò)展
由于vector3是Unity3d中非常常見(jiàn)的數(shù)據(jù)類(lèi)型,因此在這里我舉例把vector3類(lèi)型擴(kuò)展到PlayerPrefs里面.
/// <summary>
/// 存儲(chǔ)Vector3類(lèi)型的值
/// </summary>
public static bool SetVector3(string key, Vector3 vector)
{
return SetFloatArray(key, new float[3] { vector.x, vector.y, vector.z });
}
/// <summary>
/// 讀取Vector3類(lèi)型的值
/// </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原來(lái)的代碼里面,就能保存和讀取Vector3類(lèi)型的數(shù)據(jù)了,其他類(lèi)型的擴(kuò)展類(lèi)似,就不貼代碼了.