Find parent SerializedProperty
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using System.Text.RegularExpressions; | |
using UnityEditor; | |
namespace Monry | |
{ | |
public static class SerializedPropertyExtensions | |
{ | |
public static SerializedProperty FindParentProperty(this SerializedProperty serializedProperty) | |
{ | |
var propertyPaths = serializedProperty.propertyPath.Split('.'); | |
if (propertyPaths.Length <= 1) | |
{ | |
return default; | |
} | |
var parentSerializedProperty = serializedProperty.serializedObject.FindProperty(propertyPaths.First()); | |
for (var index = 1; index < propertyPaths.Length - 1; index++) | |
{ | |
if (propertyPaths[index] == "Array" && propertyPaths.Length > index + 1 && Regex.IsMatch(propertyPaths[index + 1], "^data\\[\\d+\\]$")) | |
{ | |
var match = Regex.Match(propertyPaths[index + 1], "^data\\[(\\d+)\\]$"); | |
var arrayIndex = int.Parse(match.Groups[1].Value); | |
parentSerializedProperty = parentSerializedProperty.GetArrayElementAtIndex(arrayIndex); | |
index++; | |
} | |
else | |
{ | |
parentSerializedProperty = parentSerializedProperty.FindPropertyRelative(propertyPaths[index]); | |
} | |
} | |
return parentSerializedProperty; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this won't work if a middle element is an array (always returns it). fix: