If I create a project that wants to save data to an external file - how is this done in a Unity app? e.g. Save/Load user preferences in a INI file or retain game progress, level info and anything else that might be useful to have in permanent storage. I know I can read in text data via TextAsset but how do I write out data and control the formatting (as in a INI file)?
You'll have to use C#'s StreamReader and StreamWriter. Have to create your own method of writing and parsing the data though.
I don't suppose anyone has already done this and created a few File i/o classes/functions that we can just plug into our projects?
Have a look at the various functions in System.IO. Note that this is related to Mono (.net), not C#. --Eric
The more I grapple with this thing, the more fragmented the information sources seem to be and the steeper the learning curve becomes. <sigh> I dunno where on earth I got the idea this was going to be easy. Thanks Eric for your pointer.
I just posted a sample StreamReader last night, check out the Road Reader class for how to read a text file from your asset bundle. http://forum.unity3d.com/viewtopic.php?p=232729#232729 I didn't know anything about .net I/O until I started this last night, though having 30 years of programming experience helped me to figure out the best (?) direction to go as I was learning. Managed code is a lot easier than the old way, but the learning curve is indeed fiercer. dotnet / C# programming is the summation of 40 years of API and language design and the concepts are not easy to understand. But with practice comes competency!
I just made a blog post showing some code how to do File I/O in a platform-independent way (working on both PC, Mac, iOS and Android): http://www.previewlabs.com/file-io-in-unity3d/
As erique pointed out here, since Unity 3.3 there's a way to do it without platform-specific code using #if statements. Check the updated blog post for more information.
It is, actually. In your project settings set API Compatibility Level to .Net 2.0 and then use the standard .Net I/O functionality. How to write files: Code (csharp): using (var writer = new BinaryWriter(File.Open(filename, FileMode.CreateNew))) { writer.Write(123); writer.Write(123.456f); writer.Write("Hello, World!"); } How to read files: Code (csharp): using (var reader = new BinaryReader(File.Open(filename, FileMode.Open))) { var integer = reader.ReadInt32(); var real = reader.ReadSingle(); var text = reader.ReadString(); } Also check File.ReadAllText, File.ReadAllLines, File.WriteAllText, File.WriteAllLines inside System.IO namespace.
I've been looking into generating levels from text files and wondered where to find the System.IO api reference. Invaluable, thanks!