我想为我的一个脚本编写自定义检查器。我要更改的只是要弹出的字符串之一的输入法(因此,每次我从预制的字符串列表中选择它时,而不是编写整个字符串,例如枚举)。但问题是它是一个非常长的检查器,有很多变量,只为这个输入重写所有内容对我来说并没有点击。我对默认检查器显示所有字段的方式非常满意,期待我想要更改的这个字符串。有没有办法在不自己重写整个检查器的情况下做到这一点?
问问题
137 次
1 回答
3
而不是像你提到的那样实现一个有点矫枉过正的全新 Inspector,你应该只为该字段使用PropertyDrawer 。
这很大程度上取决于您从哪里获得可用选项。一般来说,我会例如实施一个习惯PropertyAttribute
[AttributeUsage(AttributeTargets.Field)]
public class SelectionAttribute : PropertyAttribute
{
public int Index;
}
使用自定义PropertyDrawer
并将此抽屉放在名为的文件夹中Editor
[CustomPropertyDrawer(typeof(SelectionAttribute))]
public class SelectionAttributDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
// The 6 comes from extra spacing between the fields (2px each)
return EditorGUIUtility.singleLineHeight;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
position = EditorGUI.PrefixLabel(position, GUIUtility.GetControlID(FocusType.Passive), label);
if (property.propertyType != SerializedPropertyType.String)
{
EditorGUI.HelpBox(position, "Only works with string", MessageType.Error);
return;
}
//TODO: somewhere you have to get the options from
var options = new[] { "A", "B", "C", "D", "E" };
if (options == null || options.Length < 1)
{
EditorGUI.HelpBox(position, "No options available", MessageType.Error);
return;
}
var selectionAttribute = (SelectionAttribute)attribute;
EditorGUI.BeginProperty(position, label, property);
EditorGUI.BeginChangeCheck();
selectionAttribute.Index = EditorGUI.Popup(position, options.ToList().IndexOf(property.stringValue), options);
if (EditorGUI.EndChangeCheck())
{
property.stringValue = options[selectionAttribute.Index];
}
EditorGUI.EndProperty();
}
}
现在你可以在你的项目中在多个类中使用它,例如
public class Example : MonoBehaviour
{
[Selection] public string MySelection;
private void Start()
{
Debug.Log(MySelection);
}
}
无需自定义编辑器
于 2019-08-08T11:49:41.667 回答