0
public void savePreset(string doc)
{
    using (StreamWriter writetext = new StreamWriter(doc))
    {
        writetext.Write(player.transform.position.x + ", ");
        writetext.Write(player.transform.position.y + ", ");
        writetext.Write(player.transform.position.z + ", ");
        writetext.Write(player.transform.rotation.w + ", ");
        writetext.Write(player.transform.rotation.x + ", ");
        writetext.Write(player.transform.rotation.y + ", ");
        writetext.Write(player.transform.rotation.z);

        writetext.Close();
    }    
}

Basically this code reads from my txt file(doc) and then writes the values of my player rotation and position into this txt file.

However, this replaces the first line of data every time i run this savePreset. How do i save the text inside so that it saves row by row instead of replacing the first row everytime i save?

Randy Levy
  • 22,566
  • 4
  • 68
  • 94
xalvin
  • 113
  • 1
  • 13
  • look at [`System.IO.File.AppendText` method.](https://msdn.microsoft.com/en-us/library/system.io.file.appendtext%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396) – Zohar Peled Jul 14 '15 at 07:10
  • Thanks this solves the issue of not replacing my text. But how do I save it on the next line? So that the txt looks more clean – xalvin Jul 14 '15 at 07:23

3 Answers3

2

the Write() method does not write a trailing Line Feed, for that you want to use WriteLine()

from Zohar Peled's link:

    using (StreamWriter sw = File.AppendText(path)) 
    {
        sw.WriteLine("This");
        sw.WriteLine("is Extra");
        sw.WriteLine("Text");
    }   
TJennings
  • 432
  • 3
  • 14
0

You should instantiate the StreamWriter using the File.AppendText(string) method instead of directly creating a StreamWriter object.

If you want to add an empty line every time you write something just add + Environment.NewLine at the end of each line or use the WriteLine(string) method.

public void savePreset(string doc)
    {
        using (StreamWriter writetext = File.AppendText(doc))
        {
            writetext.Write(player.transform.position.x + ", " + Environment.NewLine );
            writetext.WriteLine(player.transform.position.z + ", ");
            ...
            ...

            writetext.Close();
        }
    }
M.Beas
  • 141
  • 1
  • 1
  • 7
0

Use WriteLine and AppendText methods from StreamWriter and File classes in the System.IO namespace to write content to a file in Unity.

Please follow the link given below to understand the implementation.

https://stackoverflow.com/a/69596704/7103882

Codemaker2015
  • 12,190
  • 6
  • 97
  • 81