Home > Mobile >  Using Unity JsonUtility with class containing arrays
Using Unity JsonUtility with class containing arrays

Time:10-28

I am creating a game in Unity that uses Tilemaps to procedurally generated a world similar to how a 2D Minecraft would work. I have two classes: Chunk which is 16x16 int array containing tile information, and Region which is 3x3 Chunk array. Chunks are used to load tiles onto the tilemap and Regions are used to save and load data to JSON files. When a player is playing, there will be a 3x3 chunk area loaded around their current chunk and a 3x3 region area loaded around their current region. The following is the classes:

//Stores tile data of a chunk
[Serializable]
public class Chunk
{
    public int[,] tiles = new int[CHUNK_SIZE, CHUNK_SIZE];
}

//Stores Chunk data of a region
[Serializable]
public class Region
{
    public Vector2Int location;
    public Chunk[,] chunks = new Chunk[REGION_SIZE, REGION_SIZE];
}

The following is the code that generates a region, fills the chunks, and then serializes it:

Region region = new Region();
    region.location = new Vector2Int(x, y);
    for (int i = 0; i < REGION_SIZE; i  )
    {
        for (int j = 0; j < REGION_SIZE; j  )
        {
            region.chunks[i, j] = GenerateChunk();
        }
    }
    string regionJson = JsonUtility.ToJson(region);

The problem I am having is that the resulting regionJson string only contains the position information and not the chunks information. I know the JsonUtility is minimal and has problem with arrays, however I thought wrapping an array within a class solves this issue. What I'm trying to figure out is if the problem is from the Chunk class containing an array, the Region class containing an array of Chunks, or something totally else. Any help is greatly aprreciated!

CodePudding user response:

I would not pull my hair to make a workaround to use JsonUtility in this scenario when JsonNet does it simply for me.

using Newtonsoft.Json;
string regionJson = JsonConvert.SerializeObject(region);

I've tested your scenario by generating some fake data and it works perfectly with multi-dimensional arrays.

  • Related