C# 使用JsonUtility序列化二维数组
所以我不想用Unity JSON实用程序保存一些数据,但我有一些麻烦 我有一个世界级,里面有一些参数,比如宽度、高度等,还有一个2D“Tiles”数组,这是另一个类 简化版本:C# 使用JsonUtility序列化二维数组,c#,json,unity3d,serialization,C#,Json,Unity3d,Serialization,所以我不想用Unity JSON实用程序保存一些数据,但我有一些麻烦 我有一个世界级,里面有一些参数,比如宽度、高度等,还有一个2D“Tiles”数组,这是另一个类 简化版本: public class World { [SerializeField] private Tile[,] tiles; public Tile[,] Tiles { get { return tiles; } protected set { } } [SerializeField] private int width
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);
}
瓷砖已经可以序列化了,如果我制作一个1D数组,我可以保存它们并从中获取数据,但我不知道如何使用2D或如何更改它(它是2D,因为我使用X和Y坐标获取它们)
此外,我并不真正理解JSON是如何在世界中包装这些分片的,以及分片中的内容等等。自Unity serializer以来,您可以执行以下操作:
- 将二维阵列转换为一维阵列
- 序列化为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];
}
}
}
namespace ConsoleApp2
{
内部静态类程序
{
私有静态void Main(字符串[]args)
{
//生成二维阵列样本
常数int w=3;
常数int h=5;
var i=0;
var源=新整数[w,h];
对于(变量y=0;y
结果:
请注意,您需要在JSON中序列化数组的宽度和高度