在Unity3d中,遊戲的存檔與讀檔主要由PlayerPrefs類來完成,在Windows下PlayerPrefs存檔主要存儲在註冊表中,路徑爲HKCU\Software[company name][product name] ,這裏的company name和product name由作者自己確定,在Edit->Project Settings->Player中可以設置
PlayerSettings視圖
那麼如何設計遊戲存檔呢?
以筆者個人的經驗而言,在遊戲設計之初,我們就應該想好需要存檔的數據,爲需要保存的數據或狀態設計可供讀取的狀態標誌,以便以後在設計存檔時,提供給PlayerPrefs類的方法使用。
PlayerPrefs類提供如下方法供設計者使用
可以看到,PlayerPrefs類中沒有提供對bool型數據的存儲方法,由此可以看出爲需要保存的數據或狀態設計可供讀取的狀態標誌的重要性,否則那些由bool型數據確定的狀態將無法被存檔。
下面給一段示例代碼:
/*
* inventory.charge--int--能量電池數量
* inventory.playerTransform--float--玩家位置
* talk.yeshu--int--man的任務進度
* talk.wyeshu--int--women的任務進度
*/
void gameSave() {
PlayerPrefs.SetInt("charge", inventory.charge);
PlayerPrefs.SetInt("yeshu", talk.yeshu);
PlayerPrefs.SetInt("wyeshu", talk.wyeshu);
PlayerPrefs.SetFloat("playerPosition.x", inventory.playerTransform.position.x);
PlayerPrefs.SetFloat("playerPosition.y", inventory.playerTransform.position.y);
PlayerPrefs.SetFloat("playerPosition.z", inventory.playerTransform.position.z);
PlayerPrefs.Save();
}
void gameRead() {
if (PlayerPrefs.HasKey("charge"))//存檔讀取的一般方式
inventory.charge = PlayerPrefs.GetInt("charge");
if (PlayerPrefs.HasKey("yeshu"))
talk.yeshu = PlayerPrefs.GetInt("yehsu");
if (PlayerPrefs.HasKey("wyeshu"))
talk.wyeshu = PlayerPrefs.GetInt("wyeshu");
if (PlayerPrefs.HasKey("playerPosition.x"))
x = PlayerPrefs.GetFloat("playerPosition.x");
if (PlayerPrefs.HasKey("playerPosition.y"))
y = PlayerPrefs.GetFloat("playerPosition.y");
if (PlayerPrefs.HasKey("playerPosition.z"))
z = PlayerPrefs.GetFloat("playerPosition.z");
inventory.playerTransform.position = new Vector3(x, y, z);
}
那麼對於已經產生的註冊表我們如何查看呢?
在Windows下通過註冊表編輯器查看註冊表,通過Win+R將呼出“運行”,輸入“regedit”即可打開註冊表編輯器在HKCU\Software[company name][product name] 路徑下即可找到我們已經生成的註冊表