【发布时间】:2022-11-08 03:14:38
【问题描述】:
我正在尝试使用反射从类中获取一个数组字段。在一个简单的字段上它可以工作,在 Array 它没有。
这是课
public abstract class Condition : ScriptableObject
{
public string Name;
public virtual bool IsVerified() { return false; }
}
public class ExampleScript : MonoBehaviour
{
[SerializeField] Condition _condition = null;
[SerializeField] Condition[] _conditions = new Condition[0];
}
[CustomPropertyDrawer(typeof(Condition))]
public class ConditionPropertyDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
EditorGUI.BeginProperty(position, label, property);
Type propertyType = GetPropertyType(property);
EditorGUI.EndProperty();
}
private Type GetPropertyType(SerializedProperty property)
{
Type parentType = property.serializedObject.targetObject.GetType();
Debug.Log($"{parentType} => {property.propertyPath}");
FieldInfo fi = parentType.GetField(property.propertyPath, BindingFlags.NonPublic | BindingFlags.Instance);
Debug.Log(fi);
return fi.FieldType;
}
}
这是我得到字段的地方:
Type parentType = property.serializedObject.targetObject.GetType();
Debug.Log($"{parentType} => {property.propertyPath}");
FieldInfo fi = parentType.GetField(property.propertyPath, BindingFlags.NonPublic | BindingFlags.Instance);
Debug.Log(fi);
调试打印(条件变量):
ExampleScript => _condition
MyFullNameSpace.Condition _condition调试打印(Condition[] var):
ExampleScript => _conditions.Array.data[0]
无效的为什么它不返回正确的 FieldInfo?
提前致谢
【问题讨论】:
-
您似乎正在尝试获取一个名为
"_conditions.Array.data[0]"的字段。你没有这样的领域。 (我们没有关于您从哪里获得property.propertyPath的背景信息,这使得我们很难提供进一步的帮助。) -
(如果您可以提供minimal reproducible example,通常会更容易为您提供帮助。从您所展示的内容来看,确实看起来像这样与尝试使用不是字段名称的值有关。如果现实更复杂 - 好吧,这就是一个最小的例子有助于澄清事情的地方。)
-
@JonSkeet 已更新
-
SerializedProperty.propertyPath是与SerializedObject相关的路径,它不是字段的路径。
标签: c# unity3d reflection