- Home /
Save int value to .txt file
How do I save an int variable to a text file, so when I close and open my game later my script can assess it.
Comment
You really want a file, not just to access the int again when you reload? PlayerPrefs lets you store values between games.
I didn't know that unity had this feature built in. Thanks for helping!
Answer by doug__ · Nov 25, 2012 at 03:07 PM
If you're using C# you could also look at:
System.IO.File.WriteAllText(path, value)
System.IO.File.ReadAllText(path)
...but you probably want something like this to serialize your object first:
public string SerializeXml<T>(T value) {
if(value == null) {
return null;
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UnicodeEncoding(false, false); // no BOM in a .NET string
settings.Indent = false;
settings.OmitXmlDeclaration = false;
using(StringWriter textWriter = new StringWriter()) {
using(XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) {
serializer.Serialize(xmlWriter, value);
}
return textWriter.ToString();
}
}
public T DeserializeXml<T>(string xml) {
if(string.IsNullOrEmpty(xml)) {
return default(T);
}
XmlSerializer serializer = new XmlSerializer(typeof(T));
XmlReaderSettings settings = new XmlReaderSettings();
using(StringReader textReader = new StringReader(xml)) {
using(XmlReader xmlReader = XmlReader.Create(textReader, settings)) {
return (T) serializer.Deserialize(xmlReader);
}
}
}