- Home /
How to save and load node-based tree network data to a file?
Hi, I'm working on a non-game unity project for managing production pipeline. In there I have a tree network that each node can have one input and a number of outputs. And I need to save the network in a file. How should I do that?
Thanks in advance.
Answer by duck · Apr 15, 2010 at 10:26 AM
In Unity you have full access to .net's File IO functions, which you can use to write any kind of data you like (providing you're not targeting the webplayer).
You may need to decide on some text-based format in which to encode your tree node data, and then write a 'reader' and a 'writer' which converts your tree data to and from the text format.
You could also google "c# reading and writing text files" which turns up a load of tutorials, most of which are applicable to Unity.
If you need more help, you might need to supply more detailed information about the kind of data that you want to save.
To traverse a tree system and convert it to a file-savable string, you'd want to use a recursive function call, where each call to convert a node also adds that nodes children to the string - something like this pseudocode, which uses a JSON-like format:
(untested - for illustrative purposes only)
public string Serialize() { StringBuilder s = new StringBuilder(); SerializeNode(rootNode,s); return s.ToString(); }
public void SerializeNode(Node node, StringBuilder s) { s.Append(node.name); s.Append(":["); bool firstChild = true; foreach (Node child in node.children) { if (!firstChild) { s.Append(","); } s.Append(SerializeNode(child,s); firstChild = false; } s.Append("]"); }
thanks for the reply, but my problem is not handling files. I have problem to walk through nodes in a ordered pattern for saving them.
you'll have to provide more information about the code that you're using to build the node-based data in the first place then - but essentially you'd probably want a recursive function which passes a stringbuilder reference along so that each recursion adds its own data to the end of the string, which is then written to a file.
Your answer
Follow this Question
Related Questions
How to script a Save/Load game option 17 Answers
Help with Object position and state, save and load. 1 Answer
how to make a save and load function 0 Answers
Problem Saving game progress 1 Answer