Last active
March 31, 2019 18:30
-
-
Save AdrienVR/1548a145c039d2fddf030ebc22f915de to your computer and use it in GitHub Desktop.
From https://answers.unity.com/questions/425012/get-the-instance-the-serializedproperty-belongs-to.html?childToView=425602#answer-425602 with support for SerializedDictionary
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
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.