У меня есть объект World
, который имеет некоторые ссылки на двумерный массив Tiles
и другой двумерный массив PathNodes
. И Tile
, и PathNode
являются классами, которые имеют значения и ссылку между ними. (Плитка 0,0 ссылается на узел 0,0 и т. Д.).
Я пытаюсь сохранить объект World
в JSON, сохраняя ссылки на объекты. Моя проблема в том, что когда я позже загружаю мир из JSON, тайл теряет ссылку на узел и наоборот.
World Class:
public class World
{
public Tile[,] tiles;
public PathNode[,] pathNodes;
public World(int width, int height)
{
tiles = new Tile[width, height];
pathNodes = new PathNode[width, height];
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
tiles[x, y] = new Tile(this, x, y);
pathNodes[x, y] = new PathNode(x, y);
tiles[x, y].pathNode = pathNodes[x, y];
pathNodes[x, y].tile = tiles[x, y];
}
}
}
}
Классы плиток и PathNode:
public class Tile
{
private World world;
private int x;
public int X { get { return x; } protected set { } }
private int y;
public int Y { get { return y; } protected set { } }
public Tile (World world, int x, int y)
{
this.world = world;
this.x = x;
this.y = y;
}
[JsonProperty]
public PathNode pathNode;
}
public class PathNode
{
private int x;
public int X { get { return x; } protected set { } }
private int y;
public int Y { get { return y; } protected set { } }
public PathNode(int x, int y)
{
this.x = x;
this.y = y;
}
[JsonProperty]
public Tile tile;
}
Сценарий сохранения:
public class WorldSave
{
public void SaveWorld(World worldToSave)
{
SaveSystem.Init();
string json = JsonConvert.SerializeObject(worldToSave, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
PreserveReferencesHandling = PreserveReferencesHandling.Objects
});
File.WriteAllText(SaveSystem.SAVE_FOLDER + "/Save.json", json);
}
public World LoadWorld()
{
World saveWorld = null;
if (File.Exists(SaveSystem.SAVE_FOLDER + "/Save.json"))
{
string saveString = File.ReadAllText(SaveSystem.SAVE_FOLDER + "/Save.json");
saveWorld = JsonConvert.DeserializeObject<World>(saveString, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
});
Debug.Log("Save world es: " + saveWorld);
}
return saveWorld;
}
}
JSON:
{
"$id": "1",
"tiles": [
[
{
"$id": "2",
"pathNode": {
"$id": "3",
"tile": {
"$ref": "2"
},
"X": 0,
"Y": 0
},
"X": 0,
"Y": 0
}
]
],
"pathNodes": [
[
{
"$ref": "3"
}
]
]
}
Я не думаю, что все в порядке, что плитка имеет все свойства узла, хранящиеся в нейвместо того, чтобы иметь их в разделе pathNodes
. Я не понимаю, почему это происходит.
Я использую JSON .Net для Unity