【Unity3d】简单的存档与读档



在Unity3d中,游戏的存档与读档主要由PlayerPrefs类来完成,在Windows下PlayerPrefs存档主要存储在注册表中,路径为HKCU\Software[company name][product name] ,这里的company name和product name由作者自己确定,在Edit->Project Settings->Player中可以设置
在这里插入图片描述
PlayerSettings视图
在这里插入图片描述
那么如何设计游戏存档呢?
以笔者个人的经验而言,在游戏设计之初,我们就应该想好需要存档的数据,为需要保存的数据或状态设计可供读取的状态标志,以便以后在设计存档时,提供给PlayerPrefs类的方法使用。
PlayerPrefs类提供如下方法供设计者使用
在这里插入图片描述
可以看到,PlayerPrefs类中没有提供对bool型数据的存储方法,由此可以看出为需要保存的数据或状态设计可供读取的状态标志的重要性,否则那些由bool型数据确定的状态将无法被存档。
在这里插入图片描述
下面给一段示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
* 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] 路径下即可找到我们已经生成的注册表
在这里插入图片描述


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!