Unity 使用注解通用设置Inspector窗口的显示内容

一、实现效果

        当Field:type的值为Card时,显示cardID这一栏。

    [Serializable]
    public class Reward
    {
        [SerializeField] private RewardType type;

        [SerializeField, Display(nameof(type), nameof(RewardType.Card), Operator = true)]
        private int cardID;

        [SerializeField] private int silverCount;
        [SerializeField] private int goldCount;
        [SerializeField] private int diamondCount;

    }

 

二、代码

1. Attribute:

        需继承自PropertyAttribute才能被Unity识别。

        检测使用string的形式,主要方便使用nameof()函数,Operator表示field.GetValue与TargetFieldValue的匹配方式。

    [AttributeUsage(AttributeTargets.Field)]
    public class DisplayAttribute : PropertyAttribute
    {
        public string TargetFieldName { get; }
        public string TargetFieldValue { get; }
        public bool Operator { get; set; } = true;

        public DisplayAttribute(string targetFieldName, string targetFieldValue)
        {
            this.TargetFieldName = targetFieldName;
            this.TargetFieldValue = targetFieldValue;
        }
    }

2. PropertyDrawer:

        CustomPropertyDrawer可以限定加载到相关的内容时,进行单独操作。

        通过反射找到目标的field,获取Attribute的内容。

        再根据TargetFieldName在同一个域内找到目标,使用反射获取其值并与TargetFieldValue进行对比。

        当符合条件时显示。

        这里有个Find和ParentPath的拓展方法见后文。

    [CustomPropertyDrawer(typeof(DisplayAttribute))]
    public sealed class DisplayAttributeHelper : PropertyDrawer
    {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            if (CanDisplay(property))
                EditorGUI.PropertyField(position, property, label);
        }

        public override float GetPropertyHeight(SerializedProperty property, GUIContent label) =>
            CanDisplay(property)
                ? EditorGUIUtility.singleLineHeight
                : 0;

        private static bool CanDisplay(SerializedProperty property)
        {
            var o = property.serializedObject.targetObject.Find(property.propertyPath.ParentPath());
            var type = o.GetType();
            var thisField = type.GetField(property.name,
                BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Default);
            if (thisField == null) return false;
            return thisField.GetCustomAttributes(typeof(DisplayAttribute))
                .OfType<DisplayAttribute>()
                .All(attr =>
                    !(Equals(attr.TargetFieldValue, type.GetField(attr.TargetFieldName,
                              BindingFlags.Instance
                              | BindingFlags.Public
                              | BindingFlags.NonPublic
                              | BindingFlags.Default
                          )
                          ?.GetValue(o)
                          ?.ToString()) ^
                      attr.Operator));
        }
    }

3.Extension:

        这里的内容是根据SerializedProperty.propertyPath的表现形式弄出来的。应用范围不够广。

        public static string ParentPath(this string propertyPath)
        {
            int indexOf;
            return (indexOf = propertyPath.LastIndexOf('.')) != -1 ? propertyPath.Substring(0, indexOf) : string.Empty;
        }

        public static object Find(this object obj, string actions) =>
            actions.Split('.').Aggregate(obj, (o, action) => o.InternalFind(action));

        private static readonly Regex INDEXER = new Regex(@"(?<=data\[).*(?=\])");

        private static object InternalFind(this object obj, string action)
        {
            if (obj == null) return null;
            switch (INDEXER.IsMatch(action))
            {
                case true:
                    var index = int.Parse(INDEXER.Match(action).Value);
                    var array = obj.To<Array>();
                    return array.GetValue(index);
                case false:
                    switch (action)
                    {
                        case "Array":
                            return obj.To<IEnumerable>().OfType<object>().ToArray();
                        default:
                            var type = obj.GetType();
                        {
                            var value = type.GetField(action,
                                BindingFlags.Instance
                                | BindingFlags.Public
                                | BindingFlags.NonPublic
                                | BindingFlags.Default
                                | BindingFlags.GetField)?.GetValue(obj);
                            if (value != null) return value;
                        }
                        {
                            var value = type.GetProperty(action,
                                BindingFlags.Instance
                                | BindingFlags.Public
                                | BindingFlags.NonPublic
                                | BindingFlags.Default
                                | BindingFlags.GetProperty)?.GetValue(obj);
                            if (value != null) return value;
                        }
                            return null;
                    }
            }
        }

三、总结

        上述部分功能只应用于Editor,注意代码存在的文件夹。Unity可能会报一个不重要的错误:'Editor.DisplayAttributeHelper' is missing the class attribute 'ExtensionOfNativeClass'! 不影响使用,网上的解决方法也不适用于这里。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值