From 8597ce7ebf9f18b024b6ef60419d3846f228c86e Mon Sep 17 00:00:00 2001 From: aldelaro5 Date: Sun, 15 Sep 2024 19:03:19 -0400 Subject: [PATCH] Add TomlTypeConverter for UnityEngine.Rect Originally pull request #510 Co-authored-by: ManlyMarco <39247311+manlymarco@users.noreply.github.com> --- .../UnityTomlTypeConverters.cs | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/Runtimes/Unity/BepInEx.Unity.Mono/UnityTomlTypeConverters.cs b/Runtimes/Unity/BepInEx.Unity.Mono/UnityTomlTypeConverters.cs index 3f4da2e..56f51d3 100644 --- a/Runtimes/Unity/BepInEx.Unity.Mono/UnityTomlTypeConverters.cs +++ b/Runtimes/Unity/BepInEx.Unity.Mono/UnityTomlTypeConverters.cs @@ -1,4 +1,5 @@ using System; +using System.Globalization; using System.Runtime.CompilerServices; using BepInEx.Configuration; using UnityEngine; @@ -36,5 +37,47 @@ internal static class UnityTomlTypeConverters TomlTypeConverter.AddConverter(typeof(Vector3), jsonConverter); TomlTypeConverter.AddConverter(typeof(Vector4), jsonConverter); TomlTypeConverter.AddConverter(typeof(Quaternion), jsonConverter); + TomlTypeConverter.AddConverter(typeof(Rect), new TypeConverter + { + ConvertToObject = StringToRect, + ConvertToString = RectToString + }); + } + + private static object StringToRect(string s, Type type) + { + // JsonUtility doesn't work with Rect on all Unity versions, so parse it manually + Rect result = default(Rect); + + if (s == null) + return result; + + string cleaned = s.Trim('{', '}').Replace(" ", ""); + foreach (string part in cleaned.Split(',')) + { + string[] parts = part.Split(':'); + if (parts.Length != 2 || !float.TryParse(parts[1], out float value)) + continue; + + string id = parts[0].Trim('"'); + if (id == "x") + result.x = value; + else if (id == "y") + result.y = value; + else if (id == "width" || id == "z") + result.width = value; + else if (id == "height" || id == "w") + result.height = value; + } + + return result; + } + + private static string RectToString(object o, Type type) + { + Rect rect = (Rect)o; + return string.Format(CultureInfo.InvariantCulture, + "{{ \"x\":{0}, \"y\":{1}, \"width\":{2}, \"height\":{3} }}", + rect.x, rect.y, rect.width, rect.height); } }