美文网首页
编辑器扩展基础5-自定义DecoratorDrawer

编辑器扩展基础5-自定义DecoratorDrawer

作者: JervieQin | 来源:发表于2019-02-21 21:51 被阅读0次

    介绍

    其实DecoratorDrawer有些类似PropertyDrawer(前文链接),但不完全相同。
    相同:

    • 都可以绘制自定义属性
    • 对应的Drawer都要添加[CustomPropertyDrawer]特性。

    不同:

    • DecoratorDrawer它不会改变检查器的原始行为,而是扩展它。
    • 一个属性上能加不止一个DecoratorDrawer。
    • 数组或List上加DecoratorDrawer只会对第一个起作用。
    • 继承自DecoratorDrawer

    尽管DecoratorDrawer在概念上并不意味着与特定字段相关联,但其属性仍需要放在脚本中的字段上方。

    案例:在一个字段前加上提示框

    步骤和PropertyDrawer一样,只是Drawer继承自DecoratorDrawer

    public enum HelpBoxType {
        None,
        Info,
        Warning,
        Error,
    }
    
    public sealed class HelpBoxAttribute : PropertyAttribute {
        public string Message;
        public HelpBoxType Type;
    
        public HelpBoxAttribute (string message, HelpBoxType type = HelpBoxType.None, int order = 0) {
            Message = message;
            Type = type;
            this.order = order; //PropertyAttribute.order 在多个DecoratorDrawer叠加时 设置调用次序
        }
    }
    
    using UnityEditor;
    using UnityEngine;
    
    [CustomPropertyDrawer( typeof( HelpBoxAttribute ) )]
    public sealed class HelpBoxDrawer : DecoratorDrawer
    {
        private HelpBoxAttribute HelpBoxAttribute { get { return attribute as HelpBoxAttribute; } }
    
        public override void OnGUI( Rect position )
        {
            var helpBoxPosition = EditorGUI.IndentedRect( position );
            helpBoxPosition.height = GetHelpBoxHeight();
            EditorGUI.HelpBox( helpBoxPosition, HelpBoxAttribute.Message, GetMessageType( HelpBoxAttribute.Type ) );
        }
        
        public override float GetHeight()
        {
            return GetHelpBoxHeight();
        }
    
        public MessageType GetMessageType( HelpBoxType type )
        {
            switch ( type )
            {
                case HelpBoxType.Error:     return MessageType.Error;
                case HelpBoxType.Info:      return MessageType.Info;
                case HelpBoxType.None:      return MessageType.None;
                case HelpBoxType.Warning:   return MessageType.Warning;
            }
            return 0;
        }
    
        public float GetHelpBoxHeight()
        {
            var style   = new GUIStyle( "HelpBox" );
            var content = new GUIContent( HelpBoxAttribute.Message );
            return Mathf.Max( style.CalcHeight( content, Screen.width - ( HelpBoxAttribute.Type != HelpBoxType.None ? 53 : 21) ), 40);
        }
    }
    
    public class HelpBox : MonoBehaviour {
        public int a = 0;
        [Space (22)]
        [HelpBoxAttribute ("警告:填写下面数据时需要谨慎", HelpBoxType.Warning, 2)]
        public string text = "warn";
    }
    
    效果

    总结

    到此为止,CustomPropertyDrawer的实现过程我们已经了解了。有没有发现他的好处呢?
    没错,不光个性化、它的重用性很好,做到了一次定制,到处使用。

    注:配套案例可在EditorExtensionDemo仓库中查看。

    相关文章

      网友评论

          本文标题:编辑器扩展基础5-自定义DecoratorDrawer

          本文链接:https://www.haomeiwen.com/subject/ackhyqtx.html