Since Unity 3.3, it is no longer necessary to use platform-specific code for simple file I/O. Use Application.persistentDataPath to do the trick. This code would replace the code above: string fileName = Application.persistentDataPath + '/' + FILENAME; fileWriter = File.CreateText(fileName); fileWriter.WriteLine('Hello world'); fileWriter.Close.
-->This example reads the contents of a text file by using the static methods ReadAllText and ReadAllLines from the System.IO.File class.
For an example that uses StreamReader, see How to: Read a Text File One Line at a Time.
Note
The files that are used in this example are created in the topic How to: Write to a Text File.
Example
Compiling the Code
Copy the code and paste it into a C# console application.
If you are not using the text files from How to: Write to a Text File, replace the argument to
ReadAllText
and ReadAllLines
with the appropriate path and file name on your computer.Robust Programming
The following conditions may cause an exception:
- The file doesn't exist or doesn't exist at the specified location. Check the path and the spelling of the file name.
.NET Framework Security
Do not rely on the name of a file to determine the contents of the file. For example, the file
myFile.cs
might not be a C# source file.See also
Posted by4 years ago
Archived
So I just finished my level editor mechanics a few minutes ago. Now I need to save each object's name, position and rotation. I was thinking it would be easiest to just save them in a .txt file in a 'saves' folder, so people can save levels and share them. But I have no idea how to go about creating a saves folder, creating a text file, then editing it to add the name, position and rotation of each object, then reading it all and instantiating objects using the name, position, and rotation. Where do I start?
6 comments