How does config file work?

After exporting a game, I want to change variable of the script through a config file.How does it work? Thank you.

You’d never edited a config file before? Try notepad.

Generally, you do this by:

  • Creating a plain C# class/struct that contains your config data.
  • Write the data of that C# object to disk by converting it to/from some text format, such as JSON.
  • Whenever applicable, load the text data from disk and overwrite the C# object with it.

There are many ways to go about it, but here’s a generic example:

[Serializable]
public class ConfigData {
   public Vector2 resolution;
   public bool fullscreen;
   public string language;
   //etc...
}
public class ConfigManager {
   public static ConfigData Config { get; set; }

   public void SaveConfig() {
      //Convert the ConfigData object to a JSON string.
      string json = JsonUtility.ToJson(Config);

      //Write the JSON string to a file on disk.
      File.WriteAllText("path/to/save/config.json", json);
   }

   public void LoadConfig() {
      //Get the JSON string from the file on disk.
      string savedJson = File.ReadAllText("path/to/save/config.json");

      //Convert the JSON string back to a ConfigData object.
      Config = JsonUtility.FromJson<ConfigData>(savedJson);
   }
}
4 Likes

Thank you so much. It is useful. I will have a try.