xalvin
xalvin

Reputation: 123

How do i write into a txt file row by row (Unity)

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?

Upvotes: 1

Views: 8579

Answers (3)

Codemaker2015
Codemaker2015

Reputation: 1

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

Upvotes: 0

M.Beas
M.Beas

Reputation: 173

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();
        }
    }

Upvotes: 0

Troy Jennings
Troy Jennings

Reputation: 432

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");
    }   

Upvotes: 2

Related Questions