How to modify or append data in a text file?

I have a text file which is contain information about game level ; award that you get, already played or not, the level is locked or not?

i have format like this…

1,0,0,0 <<<
first digit determine level , second is locked level , third is already played and the last one is award you get

when we pass each level , there is a script that modify the text file

i know how to read but don’t know how to write in the location in the file that i want

for example i want to modify text file at level 5 so in text file “5,0,0,1” must be modify as 5,0,1,3 (because you already played), but most tutorial that i found it creates new text file or write new line but do not mofidy existing data.

how do i suppose to do?

public void readDataFromFileByLevel(int level)
{	
	StringBuilder sb = new StringBuilder();
	
	
	using (StringReader sr = new StringReader(levelAwardFile.text)) 
    {	
	     string line;
		 while ((line = sr.ReadLine()) != null)
        {      		
			words = line.Split(',');
			if ( words.Length != 4 )
			{
				continue;
			}			
			int levelInFile = int.Parse(words[0]);	
			if ( levelInFile == level ) 
			{								    		
			    using (StringWriter sw = new StringWriter(levelAwardFile.text)) 
                {
					
				}
				
			}	
			else 
			{
				continue;
			}		
		}			
	}	
}

rather than writing data in text files you can use Player Prefs

they are much easy to read and write.

Not sure if this will help or not, but I just added saving/loading game from text to my project.

Here’s some of the lines I use when saving:

currentTrackPiece = (pieceType + "," + posX + "," + posY + "," + pieceRotationX + "," + pieceRotationY + "," + pieceRotationZ);
        
    sw.WriteLine(currentTrackPiece);

So each part of the line is a different variable, so I can have that variable change and then save it to only change that part of the line.

I hope that helps somehow…

You’ll want to use the streamreader and streamwriter classes or alternatively Unity’s TextAsset API.

works to edit single lines using system io.

function lineChanger( newText: String, fileName :String, line_to_edit: int)
{

        var arrLine : String[] = File.ReadAllLines(fileName);
        arrLine[line_to_edit - 1] = newText;
        File.WriteAllLines(fileName, arrLine);

}