unity中數據的持久化存儲


unity 提供了PlayerPrefs這個類用於存儲游戲數據到電腦硬盤中。 這個類有10個函數可以使用

Class Functions類函數

    • SetInt
      Sets the value of the preference identified by key.
      設置由key確定的參數值。
    • GetInt
      Returns the value corresponding to key in the preference file if it exists.
      如果存在,返回偏好文件中key對應的值。
    • SetFloat
      Sets the value of the preference identified by key.
      設置由key確定的參數值。
    • GetFloat
      Returns the value corresponding to key in the preference file if it exists.
      如果存在,返回游戲存檔文件中key對應的值。
    • SetString
      Sets the value of the preference identified by key.
      設置由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。
    • DeleteKey
      Removes key and its corresponding value from the preferences.
      從游戲存檔中刪除key和它對應的值。 
    • DeleteAll
      Removes all keys and values from the preferences. Use with caution.
      從偏好中刪除所有key。請謹慎使用。
    • Save
      Writes all modified preferences to disk.
      寫入所有修改參數到硬盤。

通過PlayerPrefs 類函數保存的數據都以 鍵值對集合的形式保存在硬盤中。

 

其中   set 類函數 的第一個參數為 字符串,表示要設置的數據的名稱,第二個參數就要看要保存的 數據類型了。如果想要保存一個浮點型數據,名字是 playerScore,那么應該像這樣寫:

PlayerPrefs.SetFloat("Player Score", 10.5);

同樣的如果想要博存的是int 類型的數據或者 string類型的數據,那么只需要把第二個參數指定為相應的類型就可以了。



關於get 類函數參數也有兩個。第一個必須是 sting 類型的參數,表示你要取出的值對應的鍵名稱,第二個參數則表示 如果沒找到對應的鍵的情況下返回的默認值,下面是 一個例子:

print (PlayerPrefs.GetString("Player Name","沒找到,我是默認返回值"));

像這樣,如果買有找到 PlayerName 這個鍵 ,那么將會在控制台 打印
"沒找到,我是默認返回值"

還用兩個常用的函數;

//刪除 PlayerPrefs 中某一個key的值
  PlayerPrefs . DeleteKey (“key”);
 
  //判斷 PlayerPrefs中是否存在這個key
  bool b = PlayerPrefs.HasKey(“key”);
 今天就先弄到這里吧。感覺格式上還是不太整齊,以后熟悉了會好想一些的。~~~ 
歡迎志同道合的朋友一起學習, 一起進步。



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM