UnityTomlTypeConverters.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. using BepInEx.Configuration;
  4. using UnityEngine;
  5. namespace BepInEx.Unity
  6. {
  7. /// <summary>
  8. /// Config types that are unity specific
  9. /// </summary>
  10. internal static class UnityTomlTypeConverters
  11. {
  12. [MethodImpl(MethodImplOptions.NoInlining)]
  13. public static void AddUnityEngineConverters()
  14. {
  15. var colorConverter = new TypeConverter
  16. {
  17. ConvertToString = (obj, type) => ColorUtility.ToHtmlStringRGBA((Color)obj),
  18. ConvertToObject = (str, type) =>
  19. {
  20. if (!ColorUtility.TryParseHtmlString("#" + str.Trim('#', ' '), out var c))
  21. throw new FormatException("Invalid color string, expected hex #RRGGBBAA");
  22. return c;
  23. },
  24. };
  25. TomlTypeConverter.AddConverter(typeof(Color), colorConverter);
  26. var jsonConverter = new TypeConverter
  27. {
  28. ConvertToString = (obj, type) => JsonUtility.ToJson(obj),
  29. ConvertToObject = (str, type) => JsonUtility.FromJson(type: type, json: str),
  30. };
  31. TomlTypeConverter.AddConverter(typeof(Vector2), jsonConverter);
  32. TomlTypeConverter.AddConverter(typeof(Vector3), jsonConverter);
  33. TomlTypeConverter.AddConverter(typeof(Vector4), jsonConverter);
  34. TomlTypeConverter.AddConverter(typeof(Quaternion), jsonConverter);
  35. }
  36. }
  37. }