Skip to content

Instantly share code, notes, and snippets.

@AdrienVR
Last active March 31, 2019 18:30
Show Gist options
  • Save AdrienVR/1548a145c039d2fddf030ebc22f915de to your computer and use it in GitHub Desktop.
Save AdrienVR/1548a145c039d2fddf030ebc22f915de to your computer and use it in GitHub Desktop.
public static object GetParent(this SerializedProperty prop)
{
var path = prop.propertyPath.Replace(".Array.data[", "[");
object obj = prop.serializedObject.targetObject;
var elements = path.Split('.');
foreach (var element in elements.Take(elements.Length - 1))
{
if (element.Contains("["))
{
var elementName = element.Substring(0, element.IndexOf("["));
var index = Convert.ToInt32(element.Substring(element.IndexOf("[")).Replace("[", "").Replace("]", ""));
obj = GetValueAt(obj, elementName, index);
}
else
{
obj = GetValue(obj, element);
}
}
return obj;
IEnumerable<Type> GetHierarchyTypes(Type sourceType)
{
yield return sourceType;
while (sourceType.BaseType != null)
{
yield return sourceType.BaseType;
sourceType = sourceType.BaseType;
}
}
object GetValue(object source, string name)
{
if (source == null)
return null;
foreach (var type in GetHierarchyTypes(source.GetType()))
{
var f = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (f != null)
return f.GetValue(source);
var p = type.GetProperty(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (p != null)
return p.GetValue(source, null);
}
return null;
}
object GetValueAt(object source, string name, int index)
{
var enumerable = GetValue(source, name) as IEnumerable;
var enm = enumerable.GetEnumerator();
while (index-- >= 0)
enm.MoveNext();
return enm.Current;
}
}
@AdrienVR
Copy link
Author

In my case it was not working for SerializedDictionary, my custom property drawer was associated to a property inside a dictionary value and the dictionary values are serialized in a private field of the "SerializableDictionaryBase" base class.

So I browse through all base types to look for the member and it works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment