用 PlayerPrefs 來處理玩家偏好設置

PlayerPrefs 是 Unity 引擎提供的用來存儲玩家偏好數據的模塊,可在讓運行時的數據,保存到下次開啓遊戲時使用。

這種方法如果作爲存檔來用,很容易在本地對遊戲進行篡改,會給玩家提供取巧的辦法,降低遊戲的生命力。所以 PlayerPrefs 主要作爲玩家偏好設置的保存與加載,如果每次進入遊戲都要調一遍設置,這誰受不了啊?而遊戲內容的存檔與加載不在本篇內,可以參考序列化反序列化的知識,以及解析 json 等內容,來實現遊戲中的保存和載入。

對於不同的系統會存儲在不同的位置,而使用的方法比較簡單,在想要保存數據的位置,使用 SetXXX(key, XXXvalue) 在需要使用數據的位置調用 GetXXX(key)。

如果爲了防止 key 不存在,也可以使用 GetXXX(key, defautXXXvalue) 來處理。也可以使用 HasKey(key) 來檢查是否存有 “key” 的數據。

第一個限制是保存的數據只能有 string,int,float 這三種。

關於 Save() 方法,默認情況下,Unity 在執行 OnApplicationQuit() 方法時,將數據寫入到硬盤中,爲防止意外發生,可以通過此命令將數據保存到硬盤上,但是有可能會造成一點小問題,如暫時性的延遲等,所以應該避免在遊戲流程中調用。

Windows 下數據會保存到註冊表中( HKCU\Software[company name][product name] ),這裏我分別存了兩次,因爲我發現存入的 key 後面加上了一串類似 id 的數字,本來我以爲我將 GameObject 的 ToString() 作爲 key 會將對象的 id 也打印出來(真是一個自以爲是的小夥子,打印明明看到沒有啊),所以又分割字符串,只存了 GameObject 的名字,這個“_hxxxxxxxxx”是依然存在,並不對 Get 有影響。
在這裏插入圖片描述

company name 與 product name 可以在 Unity 編輯器中找到:[Edit] - [Project Settings] - [Player] ,在 Inspector 可以看到 Company Name 與 Product Name。

有一個可視化的插件 Advanced PlayerPrefs Window,可以在編輯器中打開 PlayerPrefs 的窗口,用於設置需要保存的鍵值對。


來看看文檔,主要區別了主要的系統中,存放的位置。

On macOS PlayerPrefs are stored in ~/Library/Preferences folder, in a file named unity.[company name].[product name].plist, where company and product names are the names set up in Project Settings. The same .plist file is used for both Projects run in the Editor and standalone players.

On Windows, PlayerPrefs are stored in the registry under HKCU\Software[company name][product name] key, where company and product names are the names set up in Project Settings.

On Linux, PlayerPrefs can be found in ~/.config/unity3d/[CompanyName]/[ProductName] again using the company and product names specified in the Project Settings.

On Windows Store Apps, Player Prefs can be found in %userprofile%\AppData\Local\Packages[ProductPackageId]>\LocalState\playerprefs.dat

On Windows Phone 8, Player Prefs can be found in application’s local folder, See Also: Directory.localFolder

On Android data is stored (persisted) on the device. The data is saved in SharedPreferences. C#/JavaScript, Android Java and Native code can all access the PlayerPrefs data. The PlayerPrefs data is physically stored in /data/data/pkg-name/shared_prefs/pkg-name.xml.

On WebGL, PlayerPrefs are stored using the browser’s IndexedDB API.

On iOS, PlayerPrefs are stored in /Library/Preferences/[bundle identifier].plist.


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章