Chuyển đến nội dung
Skillpedia
Lập trình chung6.6k · #13804

save-systems

Skill này làm gì

Skill này bao quát việc lưu và tải tiến trình game, gồm những gì cần lưu, cách ghi file an toàn và đánh số phiên bản. Nó dành cho nhà phát triển cần bản lưu luôn nguyên vẹn qua các lần cập nhật.

Khi nào nên dùng

  • ✓Khi bạn cần lưu tiến trình người chơi, kho đồ và cờ thế giới giữa các phiên chơi.
  • ✓Khi bản lưu bị hỏng sau khi game sập hoặc bị gián đoạn lúc đang lưu.
  • ✓Khi các file lưu cũ ngừng hoạt động sau khi bạn cập nhật game.

Liên kết skill

https://github.com/gamedev-skills/awesome-gamedev-agent-skills/blob/main/skills/disciplines/save-systems/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/gamedev-skills/awesome-gamedev-agent-skills/blob/main/skills/disciplines/save-systems/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Người chơi của tôi bị mất file lưu khi game sập đúng lúc đang lưu, và bản lưu cũ bị hỏng sau mỗi lần cập nhật. Bạn có thể sửa hệ thống lưu không?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Agent quyết định dữ liệu nào là nguồn chuẩn và lưu chính dữ liệu đó thay vì đối tượng của engine. Nó thêm số phiên bản cho mỗi bản lưu, ghi file theo cách sập không thể làm hỏng, và thêm code chuyển đổi cho các phiên bản cũ.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Save systems

A save file is a serialized snapshot of game state that survives restarts. The hard parts aren't writing bytes — they're choosing what to save, writing it so a crash mid-save can't corrupt it, and reading old saves after you ship a patch. Get those three right and the rest is plumbing.

When to use

  • Use to persist progress: player stats, inventory, world flags, settings, positions — across sessions and game updates.
  • Use to design save slots, quicksave/autosave, and crash-safe writes.
  • Use when old save files break after a content/code change (versioning & migration).

When not to use: for Roblox cloud persistence specifics, use roblox-datastores. For the data model the save serializes (resources/SOs), use godot-resources / unity-scriptableobjects. For Godot's FileAccess/ ResourceSaver and user:// paths, defer to the Godot engine skill while applying the patterns here.

Core workflow

  1. Decide what state is authoritative. Save the data (hp, position, seed, unlocked flags), not engine objects or scene nodes. You will reconstruct objects from data on load — never serialize live node references.
  2. Define a versioned schema. Every save embeds a version integer. This is the single most important field for a game you intend to patch.
  3. Pick a format. JSON/text for readability and debuggability; a binary format for size/speed or mild tamper-resistance. Start with JSON.
  4. Write atomically. Serialize to a temp file, flush, then rename over the real file. A crash leaves either the old save or the new one — never a half-written one.
  5. Load defensively. Read version → migrate up to current → validate → instantiate. Keep a backup of the last good save and fall back on parse error.
  6. Autosave on safe boundaries (level change, checkpoint), throttled, and to a separate slot so it can't clobber a manual save.
  7. Verify: save, fully quit, relaunch, load — and confirm by inspection that state matches. Test loading a save from the previous version.

Patterns

1. Serialize state as plain data (not engine objects)

# Build a dictionary of pure data. Each savable object reports its own state.
func capture_state() -> Dictionary:
    return {
        "version": SAVE_VERSION,                 # ALWAYS stamp the schema version
        "player": { "hp": player.hp, "pos": [player.position.x, player.position.y] },
        "inventory": player.inventory.to_array(),  # ids + counts, not Item nodes
        "flags": world.flags,                    # e.g. {"met_guard": true}
        "seed": world.seed,                      # regenerate procedural content
    }

# On load, RECONSTRUCT objects from the data — do not expect live references back.
func apply_state(data: Dictionary) -> void:
    player.hp = data["player"]["hp"]
    player.position = Vector2(data["player"]["pos"][0], data["player"]["pos"][1])
    player.inventory.from_array(data["inventory"])
    world.flags = data["flags"]

2. Atomic, crash-safe write (temp + rename)

# Godot 4.7. Write a temp file, keep the previous save as .bak, then rename.
func save_atomic(path: String, data: Dictionary) -> Error:
    var tmp := path + ".tmp"
    var f := FileAccess.open(tmp, FileAccess.WRITE)
    if f == null:
        return FileAccess.get_open_error()       # disk full, read-only, no permission...
    if not f.store_string(JSON.stringify(data)):
        return ERR_FILE_CANT_WRITE
    f.close()                                    # flushes Godot's buffer to the OS
    if FileAccess.file_exists(path):
        DirAccess.rename_absolute(path, path + ".bak")   # keep the last good save
    return DirAccess.rename_absolute(tmp, path)

func load_save(path: String) -> Dictionary:      # empty = nothing loadable
    for p in [path, path + ".bak"]:              # .bak covers a crash between renames
        if FileAccess.file_exists(p):
            var data = JSON.parse_string(FileAccess.get_file_as_string(p))
            if data is Dictionary and data.has("version"):
                data["version"] = int(data["version"])   # JSON numbers load as float
                return data
    return {}
# WRONG: opening `path` directly and writing in place — a crash mid-write leaves a
# truncated, unloadable save and destroys the player's progress.

A crash now leaves the old save, the new one, or (between the two renames) only the .bak — which the loader tries

Câu hỏi thường gặp

Vì sao thêm số phiên bản vào mỗi bản lưu?

Skill gọi đây là trường quan trọng nhất, vì nó cho phép các bản cập nhật sau chuyển đổi bản lưu cũ.

Tôi có nên lưu các đối tượng trong cảnh không?

Không. Skill nói hãy lưu dữ liệu và dựng lại đối tượng từ dữ liệu đó khi tải.

Skill có bao quát lưu của Roblox không?

Không. Data store của Roblox do một skill Roblox riêng bao quát.

Chi tiết

Mô tả gốc của tác giả

Design save/load for game state — choosing what to serialize, file formats, save slots, atomic crash-safe writes, schema versioning and migration, and autosave. Engine-neutral. Use when the user mentions save system, save/load, game state persistence, save slots, autosave, save file corruption, or migrating old saves to a new version.

repo: gamedev-skills/awesome-gamedev-agent-skills

Độ phổ biến

Sao GitHub
6.6k
Vị trí xếp hạng
#13804
Giấy phép
Apache-2.0
Cập nhật
28/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự