Menu
CoddyTech

选择并删除存档槽

本课属于 Coddy Unity 学习旅程的“Unity 游戏架构”单元。第 34 课,共 64 课。

本章将存档写入 JSON:使用 [System.Serializable] 存档类,将文件保存在 Application.persistentDataPath 中,并使用字段初始化器补上旧存档中缺少的内容。现在,存档槽菜单还剩最后两个控件。

challenge icon

挑战

中等

让玩家选择一个存档槽并删除它。

  1. 在 Update() 中,按下方向键会让 selected 加 1,按上方向键会让它减 1,并用 Mathf.Min 和 Mathf.Max 将其限制在 0 到 2 之间。然后调用 Show()。
  2. DeleteSelected() 使用 File.Delete 删除所选存档槽的文件,将该存档槽设为 null,并调用 Show()。

点击“开始”,填入存档槽 3 的内容,再点击“删除”:它会显示为空。然后点击“检查”。

亲手试试

using System.IO;
using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;

public class SlotMenu : MonoBehaviour
{
    public TMP_Text[] slotTexts;
    private SlotSave[] slots = new SlotSave[3];
    private int selected;

    void Start()
    {
        for (int i = 0; i < slots.Length; i++)
        {
            if (File.Exists(PathFor(i)))
            {
                slots[i] = JsonUtility.FromJson<SlotSave>(File.ReadAllText(PathFor(i)));
            }
        }
        Show();
    }

    void Update()
    {
        // 用方向键选择存档槽位
        if (Keyboard.current.spaceKey.wasPressedThisFrame)
        {
            if (slots[selected] == null)
            {
                slots[selected] = new SlotSave();
            }
            else
            {
                slots[selected].day++;
                slots[selected].gold += 15;
            }
            File.WriteAllText(PathFor(selected), JsonUtility.ToJson(slots[selected]));
            Show();
        }
    }

    // Delete 按钮会调用这个方法
    public void DeleteSelected()
    {
    }

    string PathFor(int index)
    {
        return Path.Combine(Application.persistentDataPath, "slot" + (index + 1) + ".json");
    }

    void Show()
    {
        for (int i = 0; i < slots.Length; i++)
        {
            string line = "Slot " + (i + 1) + ": ";
            if (slots[i] == null)
            {
                line += "empty";
            }
            else
            {
                line += "Day " + slots[i].day + ", " + slots[i].gold + " gold";
            }
            if (i == selected)
            {
                line = "> " + line;
            }
            slotTexts[i].text = line;
        }
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

Unity 游戏架构中的所有课

自己练习: Unity 在线编辑器