Serializing a 2D array with JsonUtility

微笑、不失礼 提交于 2021-02-11 14:59:55

问题


so Im tryint to save some data with the Unity JSON utilities but Im having some trobles.

I have a World class that inside has some parameters like Width Height etc, and a 2D array of "Tiles", that its another class

Reduced version:

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;
    }
}
}

And in another script I have the save system, currently Im trying to save this world with its tiles:

    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 are already with Serializable, and if I make an 1D array I can save them and get data from them, but I dont know how to do it with 2D or how could I change it (its 2D because I get them with X and Y coordinates).

Also, I dont really undestand how JSON wraps this tiles inside the world, and things inside the tiles and so on.


回答1:


Since Unity serializer does not support multi-dimensional array, you can do the following:

  • convert 2D array to 1D array
  • serialize to JSON
  • deserialize from JSON
  • convert 1D array back to 2D array

Example:

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];
        }
    }
}

Result:

Note that you will need to seralize width and height of your array in JSON.



来源:https://stackoverflow.com/questions/58559529/serializing-a-2d-array-with-jsonutility

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!