Save a variable in external file (save/load)

Hello. This is probably asked many times but I searched and I can’t find exactly what I want. I have five levels in my game and, right now, the player has to go from first to last level, and there he finishes it.

I want to create an external file that will have a number inside of it (1 to 5). This can be .txt, .xml or anything else. The important thing is that unity can get a number from that file, change it and save it back.

I hope you understand what I’m trying to say. If the file contains number 2, that means that the player passed the second level.

Does anyone have this script (or anything similar) to share it with me? Thank you very much.

normally you would use player prefs for this

here’s a quick example that creates a file and then reads from it, if you still want to use file

function writeStuffToFile(){
  var stuff : String = "stuff";
  File.WriteAllText(Application.dataPath +"/stuff.txt",stuff);
} 

function readStufFromFile(){
  var stuff : String;
  stuff = File.ReadAllText(Application.dataPath +"/stuff.txt");
  Debug.Log(stuff);
}

Thank you for your reply. I tested this code (readStufFromFile) but there’s a problem

function Start () {
readStufFromFile();
}

function readStufFromFile(){
  var stuff : String;
  stuff = File.ReadAllText(Application.dataPath +"/stuff.txt");
  Debug.Log(stuff);
}

There’s a problem with this line:

stuff = File.ReadAllText(Application.dataPath +"/stuff.txt");

It says: “Unknown indentifier: ‘File’”

Can you please help me with this. Thank you one more time.

my bad:
you need to import System.IO
so, it would be

import System.IO;

function writeStuffToFile(){
  var stuff : String = "stuff";
  File.WriteAllText(Application.dataPath +"/stuff.txt",stuff);
} 

function readStufFromFile(){
  var stuff : String;
  stuff = File.ReadAllText(Application.dataPath +"/stuff.txt");
  Debug.Log(stuff);
}
2 Likes

This works!!! You can’t believe how happy this makes me… Thank you very much. I went trough a lot of trouble and then you just give me a simple answer and solve all my problems. Thank you again.