- Home /
How do I read read from and write to a text file?
WIll "System.IO" also work on a Mac?
If somebody could explain exactly how this works, thanks
Unity uses mono. $$anonymous$$ono uses a port of thethe .NET framework. This is made by $$anonymous$$icrosoft, but is platform independent. This framework is gigantic and contains nearly everything that is essential to program$$anonymous$$g.
When it comes to actually do it, check out fireDudes example.
Full easy howto http://answers.unity3d.com/answers/40481/view.html
Answer by fireDude67 · Jul 10, 2011 at 10:03 PM
public TextAsset asset; // Assign that variable through inspector
private string assetText;
void Start() {
assetText = asset.Text; // The assetText variable contains the text
// If you're looking to extract data from that,
// I would say go with XML. Otherwise, use the
// System.Regex class
}
Writing to the text file is quite a bit more difficult. However, here is another method that requires a bit of setup and isn't exactly good practice...make sure to add using UnityEngine
at the top. The text file you're reading/writing from needs to go into a special directory called "Resources"
.
public string FileName; // This contains the name of the file. Don't add the ".txt"
// Assign in inspector
private TextAsset asset; // Gets assigned through code. Reads the file.
private StreamWriter writer; // This is the writer that writes to the file
void AppendString(string appendString) {
asset = Resources.Load(FileName + ".txt") as TextAsset;
writer = new StreamWriter("Resources/" + FileName + ".txt"); // Does this work?
writer.WriteLine(appendString);
}
In Update()
use the AppendString()
function to write text.
Yes, System.IO
works on Mac
Wow, this looks very complicated. Though relatively it actually isn't. 8P
Thank you for spending the time to put this togeather. I don't completly understand it, but I will ask you some questions I have later.
One thing is, is it possible to have the plain-text file not end in .txt?
Again, thank you so much!
What you're doing here is reading from the resources folder, but can you even write to that (at run-time)?
@$$anonymous$$eavon yes. Look here:http://msdn.microsoft.com/en-us/library/system.io.file.aspx it can basically be any format you want. I use it for instance sometimes to dynamically write .js scripts.
Is TextAsset
gonna complain if I give it something other than a .txt file? I don't know. However, the writing part will work.
Okay, so I'm going to try doing this now. $$anonymous$$y first question is, what is this resource folder? What is the directory I should make it in in my project?
TextAsset won't complain if it's an other text file (like .js)
@$$anonymous$$eavon If you don't know something, first look it up in the docs. ;) http://unity3d.com/support/documentation/ScriptReference/Resources.html