【发布时间】:2020-07-29 22:48:13
【问题描述】:
对于我的统一项目,我正在尝试制作一个自定义属性抽屉,以使检查器接受仅实现我通过属性参数传递的接口的对象。我很高兴我圆满地完成了 MonoBehaviour 对象的任务。但是,我在为可编写脚本的对象应用类似方法时遇到了麻烦。我需要帮助。
这是我的财产抽屉代码。问题是 C# 不允许我使用“is”关键字进行类型检查。这是我尝试过的几个代码
if(temp_SO is requiredAttribute.requiredType) {}
if(temp_SO is T) {}
if(temp_SO.GetType().Equals(requiredAttribute.requiredType) {}
但一切都失败了...
但是,如下面的代码所示,如果我像if(temp_SO is interface_C) 那样对其进行硬编码,那么它就可以工作。我找不到动态传递类型值的方法。因为 IDE 不断抛出“一个常量值是预期的”错误。任何帮助将不胜感激。谢谢..
[CustomPropertyDrawer(typeof(SOInterfaceExposeAttribute))]
public class SOInterfaceExposeAttributeDrawer : PropertyDrawer
{
Type T;
public override void OnGUI ( Rect position , SerializedProperty property , GUIContent label )
{
if ( property . propertyType == SerializedPropertyType . ObjectReference )
{
var requiredAttribute = this . attribute as SOInterfaceExposeAttribute;
T = requiredAttribute . requiredType;
var lastValidRef = property . objectReferenceValue;
EditorGUI . BeginProperty(position , label , property);
ScriptableObject temp_SO = EditorGUI . ObjectField(position , label , property . objectReferenceValue , typeof(ScriptableObject) , true) as ScriptableObject;
// Finish drawing property field.
if ( temp_SO != null )
{
if ( temp_SO is Interface_C)
{
Debug . Log("interface component found");
property . objectReferenceValue = temp_SO as ScriptableObject;
}
else
{
Debug . Log("interface component NOT found");
property . objectReferenceValue = lastValidRef;
}
}
EditorGUI . EndProperty();
}
else
{
// If field is not reference, show error message.
// Save previous color and change GUI to red.
var previousColor = GUI . color;
GUI . color = Color . red;
// Display label with error message.
EditorGUI . LabelField(position , label , new GUIContent("Property is not a reference type"));
// Revert color change.
GUI . color = previousColor;
}
}
}
【问题讨论】:
标签: c# unity3d interface properties drawer