Skip to content

存档、配置与版本迁移 ​

存档不是把几个变量写进文件就完了。玩家可能断电,旧版本存档可能缺字段,文件可能被手改,导出后 res:// 还不能写。

一句话先记住:玩家进度写 user://,存档要带版本,写入要能从中断里恢复。


一、存档和配置分开 ​

不要把所有东西塞一个文件。

text
存档: 关卡进度、金币、背包、检查点
配置: 分辨率、音量、语言、按键映射

推荐路径:

text
user://saves/slot_1.json
user://config.cfg

存档有槽位和版本迁移。配置只有一份,坏了可以恢复默认。


二、用 user:// ​

res:// 是项目资源目录,导出后通常只读。运行时文件写到:

text
user://

Godot 会按平台映射到合适位置。你不需要自己拼系统路径。

保存前确保目录存在:

gdscript
DirAccess.make_dir_recursive_absolute("user://saves/")

三、JSON 适合玩家进度 ​

玩家进度优先用 JSON:

json
{
  "schema_version": 1,
  "level_id": "level_01",
  "checkpoint_id": "start",
  "gold": 35,
  "inventory": ["potion", "key_red"]
}

好处:

  • 人能看懂。
  • 迁移方便。
  • 不依赖 GDScript 类路径。
  • 出问题时容易排查。

Resource 更适合只读配置和内容数据,比如武器表、敌人参数、掉落表。玩家本地存档不要轻易做成带脚本的 .tres。


四、一个最小 SaveSystem ​

做成 Autoload:

gdscript
# res://systems/save_system.gd
extends Node

const SAVE_DIR := "user://saves/"
const CURRENT_SCHEMA_VERSION := 2

func save_game(slot: int, state: Dictionary) -> bool:
    DirAccess.make_dir_recursive_absolute(SAVE_DIR)

    var path := _slot_path(slot)
    var tmp_path := path + ".tmp"
    var bak_path := path + ".bak"

    state["schema_version"] = CURRENT_SCHEMA_VERSION

    var text := JSON.stringify(state, "\t")
    var file := FileAccess.open(tmp_path, FileAccess.WRITE)
    if file == null:
        push_error("Cannot write save: %s" % FileAccess.get_open_error())
        return false

    file.store_string(text)
    file.flush()
    file.close()

    if FileAccess.file_exists(path):
        if FileAccess.file_exists(bak_path):
            DirAccess.remove_absolute(bak_path)
        DirAccess.rename_absolute(path, bak_path)

    var err := DirAccess.rename_absolute(tmp_path, path)
    if err != OK:
        push_error("Cannot replace save file: %s" % err)
        return false

    return true

func load_game(slot: int) -> Dictionary:
    var path := _slot_path(slot)
    var data := _load_json(path)

    if data.is_empty():
        data = _load_json(path + ".bak")

    if data.is_empty():
        return {}

    return _migrate(data)

func _slot_path(slot: int) -> String:
    return SAVE_DIR + "slot_%d.json" % slot

func _load_json(path: String) -> Dictionary:
    if not FileAccess.file_exists(path):
        return {}

    var text := FileAccess.get_file_as_string(path)
    var parsed = JSON.parse_string(text)
    if typeof(parsed) != TYPE_DICTIONARY:
        return {}

    return parsed

写入流程是:

text
先写 .tmp
旧主文件改成 .bak
.tmp 改成主文件

这样崩在中间也不会只剩半个存档。


五、版本迁移 ​

存档里必须有:

gdscript
"schema_version": 2

迁移函数:

gdscript
func _migrate(data: Dictionary) -> Dictionary:
    var version: int = int(data.get("schema_version", 0))

    if version < 1:
        data["gold"] = int(data.get("coins", 0))
        data.erase("coins")
        version = 1

    if version < 2:
        data["inventory"] = data.get("inventory", [])
        data["checkpoint_id"] = data.get("checkpoint_id", "start")
        version = 2

    data["schema_version"] = CURRENT_SCHEMA_VERSION
    return data

只往前迁移,不要试图让新存档回到旧版本。游戏更新后,旧存档能读就行。


六、配置用 ConfigFile ​

配置文件:

gdscript
# res://systems/config_system.gd
extends Node

const CONFIG_PATH := "user://config.cfg"

var master_volume: float = 1.0
var language: String = "zh_CN"

func load_config() -> void:
    var config := ConfigFile.new()
    var err := config.load(CONFIG_PATH)
    if err != OK:
        return

    master_volume = float(config.get_value("audio", "master_volume", 1.0))
    language = str(config.get_value("game", "language", "zh_CN"))

func save_config() -> void:
    var config := ConfigFile.new()
    config.set_value("audio", "master_volume", master_volume)
    config.set_value("game", "language", language)
    config.save(CONFIG_PATH)

配置没有必要做复杂迁移。缺字段就用默认值。


七、什么时候保存 ​

推荐保存点:

text
过检查点
通关结算
回主菜单前
玩家手动保存
设置界面点应用

不推荐:

text
每帧保存
每次金币变化立刻写磁盘
战斗结算到一半保存
拖拽物品拖到一半保存

存档应该发生在稳定状态。必要时用 call_deferred() 把保存推迟到当前帧结束。


八、手改存档怎么办 ​

单机游戏里,玩家总能改本地文件。你可以选择:

text
完全不防: JSON 明文,方便 mod 和调试
轻度防: 导出版加密,编辑器版明文
强防: 服务端权威,本地只缓存

独立单机项目通常选前两种。不要把“防玩家改金币”做成比游戏本身更复杂的系统。


验收 ​

  • 存档写到 user://saves/,不是 res://。
  • 存档包含 schema_version。
  • 读取旧版本时能补默认字段。
  • 写入使用 .tmp 和 .bak。
  • 配置和存档分开。
  • 主存档损坏时能尝试读取备份。

常见坑 ​

坑 1:直接覆盖主存档。

写到一半崩溃,文件就坏了。先写 tmp。

坑 2:存档不带版本。

第一版能跑,第二版开始痛苦。

坑 3:把配置塞进存档。

玩家删档不应该丢语言和音量。

坑 4:用 Resource 保存玩家进度。

可以,但类路径和脚本变化会变成长期负担。JSON 更稳。


下一篇把主菜单、关卡、死亡、胜利和存档串成完整闭环。