Last active
August 24, 2016 09:20
-
-
Save atil/51ee0cbef2f57765b96f523baafe861e to your computer and use it in GitHub Desktop.
A general purpose configuration file boilerplate
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; | |
using UnityEngine; | |
using System.Collections; | |
using System.IO; | |
using System.Runtime.Serialization; | |
using System.Xml.Serialization; | |
[Serializable] | |
public class ApplicationConfig | |
{ | |
private const string FileName = "ApplicationConfig.xml"; | |
// Configuration properties go here | |
private static ApplicationConfig _instance; | |
public static ApplicationConfig Instance | |
{ | |
get | |
{ | |
if (_instance == null) | |
{ | |
_instance = LoadFromFile(); | |
if (_instance == null) | |
{ | |
LoadDefaultsAndSave(); | |
} | |
return _instance; | |
} | |
return _instance; | |
} | |
} | |
private static void LoadDefaultsAndSave() | |
{ | |
_instance = new ApplicationConfig() | |
{ | |
// Loading default values go here | |
}; | |
_instance.Save(); | |
} | |
public bool Save() | |
{ | |
XmlSerializer serializer = new XmlSerializer(typeof(ApplicationConfig)); | |
try | |
{ | |
using (var fs = System.IO.File.Open(FileName, FileMode.Create, FileAccess.Write)) | |
{ | |
serializer.Serialize(fs, this); | |
return true; | |
} | |
} | |
catch (Exception ex) | |
{ | |
Debug.LogError("Could not Save applicationconfig " + ex); | |
return false; | |
} | |
} | |
private static ApplicationConfig LoadFromFile() | |
{ | |
if (!File.Exists(FileName)) | |
{ | |
return null; | |
} | |
XmlSerializer serializer = new XmlSerializer(typeof(ApplicationConfig)); | |
try | |
{ | |
using (var fs = System.IO.File.Open(FileName, FileMode.Open, FileAccess.Read)) | |
{ | |
return serializer.Deserialize(fs) as ApplicationConfig; | |
} | |
} | |
catch (Exception ex) | |
{ | |
Debug.LogError("Could not Load applicationconfig " + ex); | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment