unity 使用Attribute自定义一个HeaderAttribute效果

[AttributeUsage(AttributeTargets.Field,AllowMultiple = true,Inherited = true)]
public Class TitleAttribute : PropertyAttribute{
    public string title;
    public string color;//这里不能直接用Color,会报错,不知道为什么,所以只能传16进制字符串,然后自己解析
    
    public TtileAttribute(string title,string color = "#FFFFFF"){
        this.title = title;
        this.color = color;    
    }
}

[CustomPropertyDrawer(typeof(TitleAttribute))]
public class TitleAttributeDrawer : DecoratorDrawer{
    private GUIStyle style = new GUIStyle();

    public override void OnGUI(Rect position){
        TitleAttribute ta = attribute as TitleAttribute;
        
        style.normal.textColor = GetColor(ta.color);
        style.fontSize = 30;
        position = EditorGUI.IndentedRect(position);

        GUI.Label(position,ta.title,style);
    }
    
    public override float GetHeight(){
        return base.GetHeight() + 15;
    }

    Color GetColor(string hex){
        if(string.IsNullOrEmpty(hex))
            return Color.black;

        hex = hex.ToLower();

        if(hex.IndexOf("#") == 0 && (hex.Length == 7 || hex.Length == 9)){
            //判断输入的是否是16进制颜色值,如果不是,返回黑色
            for(int i=1;i<hex.Length;i++){
                if((hex[i] >= '0' && hex[i] <= '9') == false && (hex[i] >= 'a' && hex[i] <= 'f') == false){
                    return Color.black;
                }
            }
            int r = Convert.ToInt32(hex.Substring(1,2),16);
            int g = Convert.ToInt32(hex.Substring(3,2),16);
            int b = Convert.ToInt32(hex.Substring(5,2),16);

            return new Color(r / 255.0f, g / 255.0f, b / 255.0f);
        }

        return Color.black;
    }
}

现在在字段上面加这个Attribute,即可看到效果


参考链接:https://segmentfault.com/a/1190000013174368

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值