Skip to content

JSON

unity-json-deep-dive

一句话理解

JSON 是一种“文本格式的数据”。Unity 里常用它做存档:

c
C# 对象 -> JSON 字符串 -> 写入 save.json
save.json -> JSON 字符串 -> C# 对象

JSON 长这样

c
{
  "version": 1,
  "level": 3,
  "coins": 120,
  "items": [
    { "itemId": "potion", "count": 2 }
  ]
}

它本质是:

c
key: value

比如:

c
"coins": 120
"itemId": "potion"

Unity 常用 JsonUtility

c
string json = JsonUtility.ToJson(data, true);
SaveData data = JsonUtility.FromJson<SaveData>(json);

ToJson:对象转 JSON。 FromJson:JSON 转对象。 FromJsonOverwrite:把 JSON 里的数据覆盖到已有对象上。

存档类必须这样写

c
using System;
using System.Collections.Generic;

[Serializable]
public class SaveData
{
    public int version = 1;
    public int level;
    public int coins;
    public float playerX;
    public float playerY;
    public float playerZ;
    public List<ItemSaveData> items = new();
}

[Serializable]
public class ItemSaveData
{
    public string itemId;
    public int count;
}

重点:

c
要加 [Serializable]
用字段,不要只写属性 get; set;
存纯数据,不直接存 GameObject / Transform

完整保存读取

c
using System.IO;
using UnityEngine;

public static class JsonSaveSystem
{
    private static string SavePath =>
        Path.Combine(Application.persistentDataPath, "save.json");

    public static void Save(SaveData data)
    {
        string json = JsonUtility.ToJson(data, true);
        File.WriteAllText(SavePath, json);
    }

    public static SaveData Load()
    {
        if (!File.Exists(SavePath))
            return new SaveData();

        string json = File.ReadAllText(SavePath);
        return JsonUtility.FromJson<SaveData>(json);
    }
}

Application.persistentDataPath 是 Unity 推荐用来保存持久数据的路径。

JsonUtility 的限制

Unity 官方说明 JsonUtility 使用 Unity 自己的序列化规则,所以它不是万能 JSON 库。

常见限制:

c
不能直接序列化 Dictionary
顶层不能直接是数组或 List
不能直接存 GameObject / Transform / MonoBehaviour
属性 get; set; 通常不会被序列化
字段类型必须被 Unity 序列化支持

如果要存 List,包一层:

c
[Serializable]
public class ItemListWrapper
{
    public List<ItemSaveData> items;
}

最重要的存档思想

不要存对象本身,存“能恢复对象的信息”。

错误思路:

c
保存 ItemDefinition 对象
保存 Transform 对象
保存 GameObject 对象

正确思路:

c
保存 itemId
保存 position x/y/z
保存 sceneName
保存 hp、level、coins

加载时再根据这些数据恢复游戏状态。

记住口诀:

c
JSON 是文本。
ToJson 把对象转文本。
FromJson 把文本转对象。
存档类要纯数据。
复杂对象存 ID。
路径用 persistentDataPath。

参考:Unity 官方 JsonUtility序列化规则Application.persistentDataPath

文章评价

读完这篇,留下你的看法

暂无审核通过的评价。

登录账号后才能评价。

本站访客数0总站访问量0本页访问量0