Merge pull request #510 from BepInEx/v5-rect

Add TomlTypeConverter for UnityEngine.Rect
This commit is contained in:
Geoffrey Horsington authored and GitHub committed 2022-11-15 17:33:24 +02:00
commit 73fdd058e1
1 file changed
+42
@@ -341,6 +341,48 @@ namespace BepInEx.Configuration
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} }}", new object[] { rect.x, rect.y, rect.width, rect.height });
}
}
}