Unity 3d C# saving and Loading Values

Hello everyone, I have a question. How do you save and load values in C#? I need to save a boolean, integer, and float.

To be a bit more specific I would like to save it to a file through either XML or JSON Serialization.

It depends what you mean by saving those values. If it is at runtime, just use a boolean, an integer and a float.

bool myBoolean;
int myInt;
float myFloat;

If you need to modify them outside of their scope and still have the modification applied, you need an object, class or struct.

public struct (or class) MyStruct
{
    public bool myBoolean;
    public int myInt;
    public float myFloat;
}
// Then, elswhere
MyStruct myStruct = new MyStruct();

// Then, elswhere again
myStruct.myInt++;

If you want to save them between scenes, you can use PlayerPrefs, static var or a gameObject with DontDestroyOnLoad.


Finally, if you want to save them before leaving the game and load them after it is restarted, the data must be saved on your computer. PlayerPrefs would still work, or you can take a look at xml serialization.

Save a XML:(UnityEditor only)(PC standalone Mode only)

using System.Xml;
public void SaveXML()
{
  XmlDocument xmlDoc = new XmlDocument();
  //may add Declaration
  //may add root
  XmlElement root = xmlDoc.CreateElement("", "root", "");
  xmlDoc.AppendChild(root);
  //add your data
  XmlElement xmlData = xmlDoc.CreateElement("data");
  xmlData.SetAttribute("myInt", intValue);
  xmlData.SetAttribute("myBool", intValue);
  xmlData.SetAttribute("myFlot", floatValue);
  root.AddpendChild(xmlData);
  //save
  xmlDoc.Save(yourFilePath);
}