- Home /
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.
Please be more specific. You want to save them to a file? Do you just need them on a Game Object? Depending on the answer, there are vastly different ways to do this.
Yes I would like to save it to a file. I've Heard that people use JSON or X$$anonymous$$L but I don't know how to set them up.
Answer by Berenger · Jun 11, 2012 at 12:08 AM
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.
How do you setup an X$$anonymous$$L serialization and how do you get it to save and load values?
I still have no clue how to setup an X$$anonymous$$L serialization. Is there a tutorial for how to set one up?
$$anonymous$$aybe this one ? I'm just using google, feel free to do so ;)
Ok I think I understand how it works now. but I would like to try out JSON too. How do you set it up for JSON? Also which version of JSON C# should I get?
Answer by sooncat · Jun 12, 2012 at 08:21 AM
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);
}
Your answer
Follow this Question
Related Questions
How do you save a player's prefered resolution in Unity 2017.1.1f? 0 Answers
Saving and Loading Various Things 1 Answer
Save/Load Animation State of Instantiated Prefabs 0 Answers
Save and Load Prefab and Mesh 1 Answer
webgl saving. 1 Answer