Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

How to write a file?

Discussion in 'Scripting' started by Bent, Feb 12, 2008.

  1. Bent

    Bent

    Joined:
    Feb 12, 2008
    Posts:
    34
    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
     
    Shani_T8 likes this.
  2. freyr

    freyr

    Joined:
    Apr 7, 2005
    Posts:
    1,148
    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:
    Code (csharp):
    1.  
    2. import System;
    3. import System.IO;
    4.  
    5. var  fileName = "MyFile.txt";
    6.  
    7. function Start()
    8. {
    9.         if (File.Exists(fileName))
    10.         {
    11.             Debug.Log(fileName+" already exists.");
    12.             return;
    13.         }
    14.         var sr = File.CreateText(fileName);
    15.         sr.WriteLine ("This is my file.");
    16.         sr.WriteLine ("I can write ints {0} or floats {1}, and so on.",
    17.             1, 4.2);
    18.         sr.Close();
    19. }
    20.  
     
    CyFy, kennethsauers, Ian094 and 3 others like this.
  3. Bent

    Bent

    Joined:
    Feb 12, 2008
    Posts:
    34
    freyr, that was quick!
    Thank you very much.
     
    JunSeongChoi likes this.
  4. jmunozar

    jmunozar

    Joined:
    Jun 23, 2008
    Posts:
    1,090
    And this is for reading a File :)

    Code (csharp):
    1.  
    2. import System.IO;
    3.  
    4. function ReadFile(file : String)
    5.    
    6.     if(File.Exists(file)){
    7.         var sr = File.OpenText(file);
    8.         var line = sr.ReadLine();
    9.         while(line != null){
    10.             Debug.Log(line); // prints each line of the file
    11.             line = sr.ReadLine();
    12.         }  
    13.     } else {
    14.         Debug.Log("Could not Open the file: " + file + " for reading.");
    15.         return;
    16.     }
    17. }
    18.  
     
    donalddreier85 likes this.
  5. zhapness

    zhapness

    Joined:
    Apr 10, 2011
    Posts:
    58
  6. zhapness

    zhapness

    Joined:
    Apr 10, 2011
    Posts:
    58
    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.
     
    Last edited: May 2, 2011
  7. Marcelomacm

    Marcelomacm

    Joined:
    May 21, 2013
    Posts:
    3
    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
     
  8. ar0nax

    ar0nax

    Joined:
    May 26, 2011
    Posts:
    485
    here's how you do i and search on msdn on how to open a txt file to append something to it's end.
     
    Last edited: May 21, 2013
  9. aralmo

    aralmo

    Joined:
    Aug 31, 2013
    Posts:
    1
    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.

    Code (csharp):
    1.         public static void test()
    2.         {
    3.             //this is the formatter, you can also use an System.Xml.Serialization.XmlSerializer;
    4.             var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
    5.            
    6.             //initialize some data to save
    7.             var data = new SaveData()
    8.             {
    9.                 somefloatvalue = 10.8F,
    10.                 someintvalue = 1,
    11.                 somestringvalue = "some data"
    12.             };
    13.  
    14.             //open a filestream to save on
    15.             //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.
    16.             using (Stream filestream = File.Open("filename.dat", FileMode.Create))
    17.             {
    18.                 //serialize directly into that stream.
    19.                 formatter.Serialize(filestream, data);
    20.             }
    21.  
    22.             //and now how to load that data.
    23.  
    24.             SaveData loaded_data;
    25.             //again we open a filestream but now with fileMode.Open
    26.             using (Stream filestream = File.Open("filename.dat", FileMode.Open))
    27.             {
    28.                 //deserialize directly from that stream.
    29.                 loaded_data = (SaveData) formatter.Deserialize(filestream);
    30.             }
    31.         }
    32.  
    33.         //thi is our save data structure.
    34.         [Serializable] //needs to be marked as serializable
    35.         struct SaveData
    36.         {
    37.             public int someintvalue;
    38.             public float somefloatvalue;
    39.             public string somestringvalue;
    40.         }
     
    karsnen, iegghilba and mikemonroe_oc like this.
  10. newleon

    newleon

    Joined:
    Mar 4, 2016
    Posts:
    1
    It seems the link you provided is only for VB. There is no C# example there.
     
  11. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
  12. grantsrb

    grantsrb

    Joined:
    Jan 10, 2017
    Posts:
    8
    Here's a way to save to a specific path taken from this link.

    Code (CSharp):
    1.      public static bool WriteLine (string path, string fileName, string data)
    2.      {
    3.          bool retValue = false;
    4.          try {
    5.              if (!Directory.Exists (path))
    6.                  Directory.CreateDirectory (path);
    7.              System.IO.File.WriteAllText (path + fileName, data);
    8.              retValue = true;
    9.          } catch (System.Exception ex) {
    10.              string ErrorMessages = "File Write Error\n" + ex.Message;
    11.              retValue = false;
    12.              Debug.LogError (ErrorMessages);
    13.          }
    14.          return retValue;
    15.      }
     
  13. karsnen

    karsnen

    Joined:
    Feb 9, 2014
    Posts:
    65

    Thank you for this.
     
  14. Fattie

    Fattie

    Joined:
    Jul 5, 2012
    Posts:
    474
    How to keep adding lines to a file on the desktop

    Code (CSharp):
    1. string d = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop);
    2. d = d + "/YOURLOGS";
    3.  
    4. System.IO.Directory.CreateDirectory(d);
    5. // that command means "create if not already there, otherwise leave it alone"
    6.  
    7. string filename = d + "/log.txt";
    8.  
    9. try {
    10. System.IO.File.AppendAllText(f, some_line_of_text + "\n");
    11. }
    12. catch {
    13. // careful not to create a loop of logging!
    14. }