我正在尝试创建一个通过字符串路径获取SerializedProperty的函数,然后将其转换为泛型类型并返回该函数。我尝试了很多解决方案,他们要么提供空引用或无效转换的例外。我根本不知道该怎么做。有人可以帮助我吗?谢谢! 顺便说一下这是迄今为止的功能:
T GetObjectProperty<T>(string propertyPath)
{
SerializedProperty property = serializedObject.FindProperty(propertyPath);
}
答案 0 :(得分:0)
不幸的是,Unity - SerializedProperty有许多不同的属性,例如: intValue
,floatValue
,boolValue
。
如果您在对象引用之后,因为您的函数命名对我来说听起来像是objectReferenceValue
。
否则,您必须确切地定义要访问的值;我通过将所需类型作为第二个参数传递了一次:
object GetValueByName(Type type, string name)
{
SerializedProperty property = serializedObject.FindProperty(name);
if(type == typeof(int))
{
return property.intValue;
}
else if(type == typeof(float))
{
return property.floatValue;
}
//... and so on
}
每当我使用该方法时,我只需解析就像例如。
int someValue = (int)GetValueByName(typeof(int), "XY");
如果您想坚持使用genric方法而不是返回object
并进行解析,您也可以检查typeof(T)
而不是将其作为参数:
T GetValueByName<T>(string name)
{
SerializedProperty property = serializedObject.FindProperty(name);
Type type = typeof(T);
if(type == typeof(int))
{
return property.intValue;
}
else if(type == typeof(float))
{
return property.floatValue;
}
//... and so on
}
希望这可以帮助你
(ps:如果您优先使用switch
- case
而不是多个if
- else
,请参阅this answer)