自定义 Unity 的 Property Attribute

1 首先定义特性 描述类,继承自 UnityEngine.PropertyAttribute

2 再定义特性的 绘制类,继承自 UnityEditor.PropertyDrawer,将描述类与绘制类绑定[UnityEditor.CustomPropertyDrawer(typeof(CustomRange))]

3 将特性添加到对应的 字段

1 描述类

public class CustomRange : UnityEngine.PropertyAttribute{

}

public class CustomRange : PropertyAttribute
{
    public readonly int int_max;
    public readonly int int_min;
    
    public readonly float float_max;
    public readonly float float_min;

    public readonly Color color;
    public CustomRange(float min,float max,float r,float g,float b) {
        this.float_max = max;
        this.float_min = min;
        this.color = new Color(r,g,b,1);
    }
    public CustomRange(float min, float max)
    {
        this.float_max = max;
        this.float_min = min;
        this.color = Color.white;
    }
    public CustomRange(int min, int max)
    {
        this.int_max = max;
        this.int_min = min;
        this.color = Color.white;
    }

}

2 绘制类

[UnityEditor.CustomPropertyDrawer(typeof(CustomRange))]

public class CustomeRangePropertyDrawer : PropertyDrawer {

}

[CustomPropertyDrawer(typeof(CustomRange))]
public class CustomeRangePropertyDrawer : PropertyDrawer {

    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {

        //base.OnGUI(position,property,label);
        if (property.propertyType ==  SerializedPropertyType.Float) {
            var range = attribute as CustomRange;
            GUI.color = range.color;
            //property.floatValue = EditorGUI.FloatField(position, label.text,Mathf.Clamp(property.floatValue, range.float_min, range.float_max));
            property.floatValue =  EditorGUI.Slider(position, label.text,property.floatValue,range.float_min,range.float_max);
            GUI.color = Color.white;
        }
        else if (property.propertyType == SerializedPropertyType.Integer)
        {
            var range = attribute as CustomRange;
            GUI.color = range.color;
            property.intValue = EditorGUI.IntField(position, label.text,Mathf.Clamp(property.intValue, range.int_min, range.int_max));
            //property.intValue = EditorGUI.Slider(position, label.text, property.intValue, range.int_min, range.int_max);
            GUI.color = Color.white;
        } 
    }

}

3 添加到 字段上

    [CustomRange(1f,100f,100,1,1f)]
    public float count = 0;
    [CustomRange(1, 100)]
    public int index = 0;

最终显示:

文件组织目录的要求:

CustomeRangePropertyDrawer的文件需要放在Editor目录下,否者编辑器使用没问题,但是打包会报错


参考: 

https://www.cnblogs.com/plateFace/p/4324937.html

https://mp.weixin.qq.com/s/kjoS2DaAADBUPMg1kHwnSg?

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值