Unity3d中的PlayerPrefs遊戲存檔API的擴展

功能

在遊戲會話中儲存和訪問遊戲存檔。這個是持久化數據儲存,好比保存遊戲記錄。c#

靜態函數

  • DeleteAll
    Removes all keys and values from the preferences. Use with caution. 從遊戲存檔中刪除全部key。請謹慎使用。ide

  • 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對應的浮點數值。3d

  • GetInt
    Returns the value corresponding to key in the preference file if it exists. 若是存在,返回遊戲存檔文件中key對應的整數值。code

  • 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。ip

  • Save
    Writes all modified preferences to disk. 寫入全部修改參數到硬盤。字符串

  • SetFloat
    Sets the value of the preference identified by key. 設置由key肯定的浮點數值。get

  • SetInt
    Sets the value of the preference identified by key. 設置由key鍵肯定的整數值。string

  • 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類型的數據了,其餘類型的擴展相似,就不貼代碼了.

相關文章
相關標籤/搜索