ScriptReference/SerializedProperty-propertyPath #114
Replies: 1 comment
-
|
Comment by RaspberrySpaceJam: The path returned is delimited by periods. If an object in the path is an array it will be followed by ".Array.data[index]". /// <summary>
/// Draw a custom layout for MyClass
/// </summary>
/// <param name="position">Editor window position</param>
/// <param name="property">Serialized property being drawn</param>
/// <param name="label">Property label</param>
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
MyClass class = GetValueByPath(property.serializedObject.targetObject, property.propertyPath) as MyClass;
}
/// <summary>
/// Navigates to the object at the end of the serialized property path.
/// </summary>
/// <param name="source">The serialized object target.</param>
/// <param name="path">The path to the property.</param>
/// <returns>The object at the end of the property path.</returns>
public object GetValueByPath(object source, string path)
{
string[] pathStrings = path.Split(new string[] { "." }, System.StringSplitOptions.None);
int i = 0;
while(i < pathStrings.Length && source != null)
{
if (pathStrings[i] == "Array")
{
i++;
string[] arrayStrings = pathStrings[i].Split(new string[] { "[", "]" }, System.StringSplitOptions.None);
source = ((System.Array)source).GetValue(int.Parse(arrayStrings[1]));
}
else
{
source = GetValue(source, pathStrings[i]);
}
i++;
}
return source;
}
/// <summary>
/// Returns the property, field, or value of the given name on the object.
/// </summary>
/// <param name="source">The object to find the property, field, or value on.</param>
/// <param name="name">The name of the property, field, or value.</param>
/// <returns>The property, field, or value.</returns>
public object GetValue(object source, string name)
{
if (source == null)
return null;
var type = source.GetType();
var f = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
if (f == null)
{
var p = type.GetProperty(name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
if (p == null)
return null;
return p.GetValue(source, null);
}
return f.GetValue(source);
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
ScriptReference/SerializedProperty-propertyPath
https://docs.unity3d.com/ScriptReference/SerializedProperty-propertyPath.html
Beta Was this translation helpful? Give feedback.
All reactions