unity 提供了PlayerPrefs這個類用於存儲游戲數據到電腦硬盤中。 這個類有10個函數可以使用
Class Functions類函數
-
SetIntSets the value of the preference identified by key.
設置由key確定的參數值。 -
GetIntReturns the value corresponding to key in the preference file if it exists.
如果存在,返回偏好文件中key對應的值。 -
SetFloatSets the value of the preference identified by key.
設置由key確定的參數值。 -
GetFloatReturns the value corresponding to key in the preference file if it exists.
如果存在,返回游戲存檔文件中key對應的值。 -
SetStringSets the value of the preference identified by key.
設置由key確定的參數值。 -
GetStringReturns the value corresponding to key in the preference file if it exists.
如果存在,返回游戲存檔文件中key對應的值。 -
HasKeyReturns true if key exists in the preferences.
如果key在游戲存檔中存在,返回true。 -
DeleteKeyRemoves key and its corresponding value from the preferences.
從游戲存檔中刪除key和它對應的值。 -
DeleteAllRemoves all keys and values from the preferences. Use with caution.
從偏好中刪除所有key。請謹慎使用。 -
SaveWrites 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”);
今天就先弄到這里吧。感覺格式上還是不太整齊,以后熟悉了會好想一些的。~~~
歡迎志同道合的朋友一起學習, 一起進步。
