写编辑器遇到需要通过SerializedObject的SerializedProperty获取其对应的对象(比如需要调用其方法),以下封装一个统一方法,便于以后直接使用
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System;
using System.Reflection;
public class ReflectPropertyPath : MonoBehaviour
{
[Serializable]
public class TestObject
{
[Serializable]
public class ElementLayer1
{
[Serializable]
public class ElementLayer2
{
[SerializeField]
int intData;
}
[SerializeField]
List<ElementLayer2> listData;
[SerializeField]
ElementLayer2[] arrayData;
[SerializeField]
string stringData;
}
[SerializeField]
ElementLayer1 layer1Data;
}
[SerializeField]
TestObject m_TestObject;
[ContextMenu("Run")]
void Run()
{
SerializedObject serializObject = new SerializedObject(this);
var testObjectProp = serializObject.FindProperty("m_TestObject");
var layer1DataProp = testObjectProp.FindPropertyRelative("layer1Data");
var stringDataProp = layer1DataProp.FindPropertyRelative("stringData");
Debug.Log(stringDataProp.propertyPath);
Debug.Log(GetSerializedPropertyValue(stringDataProp));
var listDataElementProp0 = layer1DataProp.FindPropertyRelative("listData").GetArrayElementAtIndex(0).FindPropertyRelative("intData");
Debug.Log(listDataElementProp0.propertyPath);
Debug.Log(GetSerializedPropertyValue(listDataElementProp0));
var arrayDataElementProp0 = layer1DataProp.FindPropertyRelative("arrayData").GetArrayElementAtIndex(1).FindPropertyRelative("intData");
Debug.Log(arrayDataElementProp0.propertyPath);
Debug.Log(GetSerializedPropertyValue(arrayDataElementProp0));
}
System.Object GetSerializedPropertyValue(SerializedProperty property)
{
if(property == null)
return null;
return GetSerializedPropertyValue(property.serializedObject, property.propertyPath);
}
System.Object GetSerializedPropertyValue(SerializedObject serializedObject, string propertyPath)
{
System.Object tempObject = serializedObject.targetObject;
var splitPaths = propertyPath.Split('.');
Array array = null;
for (int i = 0; i < splitPaths.Length; i++)
{
var splitPath = splitPaths[i];
if (splitPath == "Array")
{
var arrayType = tempObject.GetType();
if (arrayType.IsArray)
{
array = (Array)tempObject;
}
else
{
if (arrayType.Name.StartsWith("List"))
{
var _itemsField = arrayType.GetField("_items", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
tempObject = _itemsField.GetValue(tempObject);
array = (Array)tempObject;
}
}
}
else if (i > 0 && splitPaths[i - 1] == "Array" && splitPath.StartsWith("data["))
{
var arrayIndex = int.Parse(splitPath.Replace("data[", "").Replace("]", ""));
tempObject = array.GetValue(arrayIndex);
}
else
{
var propField = tempObject.GetType().GetField(splitPath, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
tempObject = propField.GetValue(tempObject);
}
}
return tempObject;
}
}
效果如下

文章评论