using System; using System.Reflection; namespace Game; [Flags] public enum ConsoleFlags { NoSerialize = 1, // Value does not persist Alias = NoSerialize } internal struct ConsoleVariable { public string name { get; } public ConsoleFlags flags { get; } private readonly FieldInfo field; private readonly MethodInfo getter; private readonly MethodInfo setter; public ConsoleVariable(string name, ConsoleFlags flags, FieldInfo field) { this.name = name; this.flags = flags; this.field = field; getter = null; setter = null; } public ConsoleVariable(string name, ConsoleFlags flags, MethodInfo getter, MethodInfo setter) { this.name = name; this.flags = flags; field = null; this.getter = getter; this.setter = setter; } public string GetValueString() { Type type = field != null ? field.FieldType : getter.ReturnType; if (type == typeof(string)) { if (field != null) return (string)field.GetValue(null); if (getter != null) return (string)getter.Invoke(null, null); } else if (type == typeof(float)) { if (field != null) return field.GetValue(null).ToString(); if (getter != null) return (string)getter.Invoke(null, null); } else throw new Exception($"Unsupported console variable type '{type.FullName}'"); throw new Exception("GetValueString no field or getter specified"); } public void SetValue(string value) { Type type = field != null ? field.FieldType : getter.ReturnType; if (type == typeof(string)) { if (field != null) field.SetValue(null, value); else if (setter != null) setter.Invoke(null, new object[] { value }); } else if (type == typeof(float)) { if (!float.TryParse(value, out var floatValue)) return; if (field != null) field.SetValue(null, floatValue); else if (setter != null) setter.Invoke(null, new object[] { floatValue }); } else { throw new Exception("Unsupported type for SetValue: " + type.Name); } } }