How to write a file?

Hi all,

I am totally new to Unity. I have been playing around with it and love how easy it is to use. However I could not find the way to write something into text file. I looked through Script Reference and did some search on the forum. All I found was TextAsset.text which was to read from a text file. I want to save some information in a text file so that I can use that file later in other program.

And also one more question, how do you save game in Unity?

Thank you.

Bent

2 Likes

The Unity documentation only documents the Unity-specific APIs.

Here’s a link to the msdn documentation about how to write text to a file:

Writing Text to a File

Code examples on that page are in Visual basic and C#. Here’s a quick translation into javascript:

import System;
import System.IO;

var  fileName = "MyFile.txt";

function Start()
{
        if (File.Exists(fileName)) 
        {
            Debug.Log(fileName+" already exists.");
            return;
        }
        var sr = File.CreateText(fileName);
        sr.WriteLine ("This is my file.");
        sr.WriteLine ("I can write ints {0} or floats {1}, and so on.", 
            1, 4.2);
        sr.Close();
}
7 Likes

freyr, that was quick!
Thank you very much.

1 Like

And this is for reading a File :slight_smile:

import System.IO;

function ReadFile(file : String)
	
	if(File.Exists(file)){
		var sr = File.OpenText(file);
		var line = sr.ReadLine();
		while(line != null){
			Debug.Log(line); // prints each line of the file
			line = sr.ReadLine();
		}	
	} else {
		Debug.Log("Could not Open the file: " + file + " for reading.");
		return;
	}
}
1 Like

|

Nice but how to read an int from the txt, or convert a string to int after reading it.

I need to read a vector 3 position, so i need to read it as an int.

thanks

EDIT:

Never mind that, i found out, now i just need to know how to read and write the txts on my ftp server.

Hi, I have this code:


sw = new StreamWriter(“Roupeiro_camisa.txt”);
sw.Write("Item escolhido: ");
sw.WriteLine(item.name);
sw.Write("Tempo: ");
sw.WriteLine(Time.time);
sw.Close();

this, write to new text file always.
But i want that insted of write to a new file, this add infomation to alredy existing file.
Help please

here’s how you do i and search on msdn on how to open a txt file to append something to it’s end.

It is better to have a save data struct and serialize it before saving the file.

I would recommend protocol buffers if you target a mobile platform or the already available JIT deppendant BinaryFormatter of .Net
The first you can find it here https://code.google.com/p/protobuf-net/.

And this is an example for the second.

        public static void test()
        {
            //this is the formatter, you can also use an System.Xml.Serialization.XmlSerializer;
            var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            
            //initialize some data to save
            var data = new SaveData()
            {
                somefloatvalue = 10.8F,
                someintvalue = 1,
                somestringvalue = "some data"
            };

            //open a filestream to save on
            //notice there is no need to close or flush the stream as it will do it before disposing at the end of the using block.
            using (Stream filestream = File.Open("filename.dat", FileMode.Create))
            {
                //serialize directly into that stream.
                formatter.Serialize(filestream, data);
            } 

            //and now how to load that data.

            SaveData loaded_data;
            //again we open a filestream but now with fileMode.Open
            using (Stream filestream = File.Open("filename.dat", FileMode.Open))
            {
                //deserialize directly from that stream.
                loaded_data = (SaveData) formatter.Deserialize(filestream);
            } 
        }

        //thi is our save data structure.
        [Serializable] //needs to be marked as serializable
        struct SaveData
        {
            public int someintvalue;
            public float somefloatvalue;
            public string somestringvalue;
        }
4 Likes

It seems the link you provided is only for VB. There is no C# example there.

Try this one instead. https://msdn.microsoft.com/en-us/library/system.io.file(v=vs.110).aspx

Unfortunately links don’t last forever.

Here’s a way to save to a specific path taken from this link.

     public static bool WriteLine (string path, string fileName, string data)
     {
         bool retValue = false;
         try {
             if (!Directory.Exists (path))
                 Directory.CreateDirectory (path);
             System.IO.File.WriteAllText (path + fileName, data);
             retValue = true;
         } catch (System.Exception ex) {
             string ErrorMessages = "File Write Error\n" + ex.Message;
             retValue = false;
             Debug.LogError (ErrorMessages);
         }
         return retValue;
     }

Thank you for this.

How to keep adding lines to a file on the desktop

string d = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
d = d + "/YOURLOGS";

System.IO.Directory.CreateDirectory(d);
// that command means "create if not already there, otherwise leave it alone"

string filename = d + "/log.txt";

try {
System.IO.File.AppendAllText(f, some_line_of_text + "\n");
}
catch {
// careful not to create a loop of logging!
}