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?
|