Created
January 8, 2022 14:14
-
-
Save MarcelvanDuijnDev/303033a206a2fc44b7f09b458885657f to your computer and use it in GitHub Desktop.
Unity Save/Load XML files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using System.Xml.Serialization; | |
using System.IO; | |
public class SaveLoad_XML : MonoBehaviour | |
{ | |
private XML_SaveData _SaveData = new XML_SaveData(); | |
void Start() | |
{ | |
LoadData(); | |
} | |
public void SaveData() | |
{ | |
XmlSerializer serializer = new XmlSerializer(typeof(XML_SaveData)); | |
using (FileStream stream = new FileStream(Application.persistentDataPath + "/SaveData.xml", FileMode.Create)) | |
{ | |
serializer.Serialize(stream, _SaveData); | |
} | |
} | |
public void LoadData() | |
{ | |
try | |
{ | |
XmlSerializer serializer = new XmlSerializer(typeof(XML_SaveData)); | |
using (FileStream stream = new FileStream(Application.persistentDataPath + "/SaveData.xml", FileMode.Open)) | |
{ | |
_SaveData = serializer.Deserialize(stream) as XML_SaveData; | |
} | |
} | |
catch | |
{ | |
SaveData(); | |
} | |
} | |
public XML_SaveData GetSaveData() | |
{ | |
return _SaveData; | |
} | |
public void CreateNewSave() | |
{ | |
XML_ExampleData newsave = new XML_ExampleData(); | |
newsave.exampleValue = 10; | |
_SaveData.saveData.Add(newsave); | |
} | |
} | |
[System.Serializable] | |
public class XML_SaveData | |
{ | |
public List<XML_ExampleData> saveData = new List<XML_ExampleData>(); | |
} | |
[System.Serializable] | |
public class XML_ExampleData | |
{ | |
public float exampleValue = 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment