From 60b109a6296a0ba7de863e1e12ca4d90f1d21d7b Mon Sep 17 00:00:00 2001 From: Jens Pitkanen Date: Fri, 7 Aug 2020 00:12:26 +0300 Subject: [PATCH] Add options de- and se-rialization --- Assets/Scripts/Options.cs | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/Assets/Scripts/Options.cs b/Assets/Scripts/Options.cs index ab954aa..1f92f03 100644 --- a/Assets/Scripts/Options.cs +++ b/Assets/Scripts/Options.cs @@ -1,19 +1,46 @@ -using System.Collections; -using System.Collections.Generic; -using UnityEngine; +using UnityEngine; +using System.IO; +using System; +using System.Xml.Serialization; namespace NeonTea.Quakeball { /// Container for user-selected options. + [XmlRootAttribute("Options")] public class OptionsData { + // DO NOT REMOVE OR CHANGE EXISTING FIELDS AFTER RELEASE TO AVOID BREAKING EXISTING CONFIGURATIONS + // New fields are fine though, the defaults will be used. public bool InvertVerticalLook = false; - public float LookSensitivity = 0.15f; + public float LookSensitivity = 0.1f; } - public class Options : MonoBehaviour { - private static OptionsData Singleton = new OptionsData(); + /// A collection of functions to access user-specific configuration. + public static class Options { + private static string OptionsDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Quakeball"); + private static string OptionsPath = Path.Combine(OptionsDirectory, "Config.xml"); + private static OptionsData Singleton = Load(); public static OptionsData Get() { return Singleton; } + + public static void Save(OptionsData options) { + XmlSerializer Serializer = new XmlSerializer(typeof(OptionsData)); + Directory.CreateDirectory(OptionsDirectory); + FileStream OptionsFile = File.Create(OptionsPath); + Serializer.Serialize(OptionsFile, options); + OptionsFile.Close(); + } + + public static OptionsData Load() { + try { + XmlSerializer Serializer = new XmlSerializer(typeof(OptionsData)); + FileStream OptionsFile = File.OpenRead(OptionsPath); + OptionsData Options = (OptionsData)Serializer.Deserialize(OptionsFile); + OptionsFile.Close(); + return Options; + } catch (Exception) { + return new OptionsData(); + } + } } }