0

I am using C# and I would like to know how to save and read a file, but I would like to save more informations, so it will be awesome if the saved file will be something like:

player-level = 1;

player-money = 100;

etc.

apxcode
  • 7,696
  • 7
  • 30
  • 41

2 Answers2

1

Use PlayerPrefs.

Example:

public class ExampleClass : MonoBehaviour 
{
    void saveScore(int score) 
    {
        PlayerPrefs.SetInt("Player Score", score);
    }

    void getScore() 
    {
        print(PlayerPrefs.GetInt("Player Score"));
    }
}
apxcode
  • 7,696
  • 7
  • 30
  • 41
1

For writing file in Unity you can use the following code snippet. It will create or append the text file in the root folder of your project

public void WriteToFile(string text)
{
    StreamWriter fileWriter;
    string fileName = GetCurrentWorkingDirectory() + "/" + "myFile.txt";
    if (!File.Exists (fileName)) {
        fileWriter = File.CreateText (fileName);
        fileWriter.WriteLine (text);
        fileWriter.Close ();
            } 
    else 
    {
        fileWriter = File.AppendText(fileName);
        fileWriter.WriteLine (text);
        fileWriter.Close ();
    }
}

For Key Value pair writing you can use XML or JSON. I would prefer JSON.

Hamza Hasan
  • 1,368
  • 9
  • 17
  • 1
    If you want to use XML or JSON, you can use C#'s own [XML serialization](http://stackoverflow.com/questions/4123590/serialize-an-object-to-xml) or [JSON serialization](http://stackoverflow.com/questions/6201529/turn-c-sharp-object-into-a-json-string-in-net-4). – maZZZu Nov 10 '14 at 08:22