0

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 Answer 1

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:

enter image description here enter image description here enter image description here

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.