【问题标题】:Serializing a 2D array with JsonUtility使用 JsonUtility 序列化二维数组
【发布时间】:2019-10-25 13:30:55
【问题描述】:

所以我尝试使用 Unity JSON 实用程序保存一些数据,但我遇到了一些问题。

我有一个 World 类,里面有一些参数,如 Width Height 等,以及一个“Tiles”的 2D 数组,它是另一个类

精简版:

public class World
{
[SerializeField]
private Tile[,] tiles;
public Tile[,] Tiles { get { return tiles; } protected set { } }

[SerializeField]
private int width;
public int Width
{
    get { return width; }
}

[SerializeField]
private int height;
public int Height
{
    get { return height; }
}
public int WorldSize
{
    get
    {
        return height * width;
    }
}
}

在另一个脚本中,我有保存系统,目前我正试图用它的瓷砖拯救这个世界:

    public void SaveWorld(World worldToSave)
    {
    SaveSystem.Init();
    string json = JsonUtility.ToJson(worldToSave);
    Debug.Log("Json es: " + json);
    //AHORA MISMO ESTO GUARDA SOLO WIDTH Y HEIGHT DEL MUNDO
    File.WriteAllText(SaveSystem.SAVE_FOLDER + "/Save.txt", json);
    }

Tiles 已经可以序列化了,如果我创建一个 1D 数组,我可以保存它们并从中获取数据,但我不知道如何使用 2D 或如何更改它(它是 2D,因为我得到它们X 和 Y 坐标)。

另外,我真的不明白 JSON 是如何将这些图块包装到世界中的,以及图块中的东西等等。

【问题讨论】:

    标签: c# json unity3d serialization


    【解决方案1】:

    由于 Unity 序列化器does not support multi-dimensional array,您可以执行以下操作:

    • 将二维数组转换为一维数组
    • 序列化为 JSON
    • 从 JSON 反序列化
    • 将一维数组转换回二维数组

    例子:

    namespace ConsoleApp2
    {
        internal static class Program
        {
            private static void Main(string[] args)
            {
                // generate 2D array sample
    
                const int w = 3;
                const int h = 5;
    
                var i = 0;
    
                var source = new int[w, h];
    
                for (var y = 0; y < h; y++)
                for (var x = 0; x < w; x++)
                    source[x, y] = i++;
    
                // convert to 1D array
    
                var j = 0;
    
                var target = new int[w * h];
    
                for (var y = 0; y < h; y++)
                for (var x = 0; x < w; x++)
                    target[j++] = source[x, y];
    
                // convert back to 2D array
    
                var result = new int[w, h];
    
                for (var x = 0; x < w; x++)
                for (var y = 0; y < h; y++)
                    result[x, y] = target[y * w + x];
            }
        }
    }
    

    结果:

    请注意,您需要在 JSON 中序列化数组的宽度和高度。

    【讨论】:

      猜你喜欢
      • 2016-01-28
      • 1970-01-01
      • 2019-10-12
      • 2017-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多