- Home /
Serialization of custom class
I'm working on rolling my own pathfinding solution using a grid of nodes. Currently it works but I want to change it so that I don't have to recalculate walkabaility of nodes for static obstacles each time at startup.
I know unity cannot serialize multidimensional arrays so my solution was to move the node array to its own class with an indexer to access the one-dimensional array as if it were 2D. I've done that and it still works when I run the method to initialise the grid. However, entering play mode (or calling it during play mode and exiting to edit mode) clears all the data.
Clearly i'm doing something wrong, I used a similar approach once before on a simple tile based map successfully, so any insight would be appreciated. Here is the relevant code stripped out:
// Grid class that should serialize
[System.Serializable]
public class Grid
{
public Node[] nodes;
public int numNodes;
public Grid (int gWidth)
{
nodes = new Node[gWidth*gWidth];
numNodes = gWidth;
}
public Node this[int x, int y] {
get { return nodes[y*numNodes+x]; }
set { nodes[y*numNodes+x] = value; }
}
}
// main class that uses the grid, stripped down to relevant parts
public class MainClass
{
[HideInInspector]
public int width, height;
[HideInInspector]
public float rawWidth, rawHeight;
[HideInInspector]
public float nodeSize; // size one node, or square, covers.
public int subDivs; // number of nodes in one column or row of the grid
public Vector3 topLeft, bottomRight; // top left and bottom right corners of the grid in world coords
public Grid grid;
public void InitGrid ()
{
//calculate width and height
rawWidth = Mathf.Abs (topLeft.x - bottomRight.x);
rawHeight = Mathf.Abs (topLeft.z - bottomRight.z);
nodeSize = rawWidth / subDivs;
grid = new Grid (subDivs);
width = subDivs;
height = subDivs;
for (int i = 0; i < width; i++)
{
for (int k = 0; k < height; k++)
{
grid[i,k] = new Node();
grid[i,k].position = new Vector3 (i * nodeSize + (nodeSize / 2), 0, k * nodeSize + (nodeSize / 2));
grid[i,k].isWalkable = true;
}
}
}
}
Sorry for the lengthy formatting, not sure why it's inserting so much white space, it doesn't exist in my code file.
Should be serialized correctly, afaik. Did you set the Node class as System.Serializable also?
EDIT: Yeah that was the problem, I hadn't set up the node to serialize properly. Thanks for pointing my silliness out!
Answer by Swiftpaw · Aug 19, 2012 at 06:17 PM
Answering my own question here to sum it all up. I hadn't properly marked my Node class with [System.Serializable], oops! Thanks for pointing it out Izitmee.
Ehe serialization is so messy sometimes. Glad you got it ;)
hah, came here because I was making the same mistake. Sometimes the simplest problems are the most frustrating!