当前位置:   article > 正文

自定义 Unity 的 Property Attribute_unity 自定义propertyattribute

unity 自定义propertyattribute

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

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

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

1 描述类

public class CustomRange : UnityEngine.PropertyAttribute{

}

  1. public class CustomRange : PropertyAttribute
  2. {
  3. public readonly int int_max;
  4. public readonly int int_min;
  5. public readonly float float_max;
  6. public readonly float float_min;
  7. public readonly Color color;
  8. public CustomRange(float min,float max,float r,float g,float b) {
  9. this.float_max = max;
  10. this.float_min = min;
  11. this.color = new Color(r,g,b,1);
  12. }
  13. public CustomRange(float min, float max)
  14. {
  15. this.float_max = max;
  16. this.float_min = min;
  17. this.color = Color.white;
  18. }
  19. public CustomRange(int min, int max)
  20. {
  21. this.int_max = max;
  22. this.int_min = min;
  23. this.color = Color.white;
  24. }
  25. }

2 绘制类

[UnityEditor.CustomPropertyDrawer(typeof(CustomRange))]

public class CustomeRangePropertyDrawer : PropertyDrawer {

}

  1. [CustomPropertyDrawer(typeof(CustomRange))]
  2. public class CustomeRangePropertyDrawer : PropertyDrawer {
  3. public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
  4. {
  5. //base.OnGUI(position,property,label);
  6. if (property.propertyType == SerializedPropertyType.Float) {
  7. var range = attribute as CustomRange;
  8. GUI.color = range.color;
  9. //property.floatValue = EditorGUI.FloatField(position, label.text,Mathf.Clamp(property.floatValue, range.float_min, range.float_max));
  10. property.floatValue = EditorGUI.Slider(position, label.text,property.floatValue,range.float_min,range.float_max);
  11. GUI.color = Color.white;
  12. }
  13. else if (property.propertyType == SerializedPropertyType.Integer)
  14. {
  15. var range = attribute as CustomRange;
  16. GUI.color = range.color;
  17. property.intValue = EditorGUI.IntField(position, label.text,Mathf.Clamp(property.intValue, range.int_min, range.int_max));
  18. //property.intValue = EditorGUI.Slider(position, label.text, property.intValue, range.int_min, range.int_max);
  19. GUI.color = Color.white;
  20. }
  21. }
  22. }

3 添加到 字段上

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

最终显示:

文件组织目录的要求:

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


参考: 

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

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

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号