• Unity 扩展属性自定义绘制


    这么晚了准备睡觉的时候,去学习了一会. 发现一个标题好奇的点进去. 居然是自定义绘制属性.  在前几天这个问题把我难住了,没想到几分钟就能解决的问题。 我花了半天时间使用反射去解决。。。  如果我们想要让属性自定义绘制窗体,首先会想到扩展InspectorEditor, 这章讲解.原来属性可以独立绘制,亮瞎我的双眼!

    如图:

    image

    步骤:

         1. 定义绘制特性描述类(以数据提供给 –> 绘制类 –> 绘制)

         2. 定义属性自定义绘制类

         3. 给一个字段添加你的特性

    1. 绘制特性描述类 

    using UnityEngine;
    using System.Collections;
    using UnityEditor;
    
    /// <summary>
    /// 必须继承PropertyAttribute
    /// </summary>
    public class MyRangeAttribute : PropertyAttribute {
        
        //绘制需要的数据
        public float min;
        public float max;
        public string label;
    
        public MyRangeAttribute(float min, float max,string label = "") 
        {
            this.min = min;
            this.max = max;
            this.label = label;
        }
    
        
    }

    2. 属性绘制类

    using UnityEngine;
    using System.Collections;
    using UnityEditor;
    
    /// <summary>
    /// 继承PropertyDrawer, 必须放入Editor文件夹下
    /// </summary>
    [CustomPropertyDrawer(typeof(MyRangeAttribute))]
    public class MyRangeAttributeDrawer : PropertyDrawer {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            //获取绘制描述类
            MyRangeAttribute range = this.attribute as MyRangeAttribute;
    
            //判断字段是那种类型,进行不同的绘制
            if(property.propertyType == SerializedPropertyType.Float)
            {
                Debug.Log("float类型");
                EditorGUI.Slider(position,property,range.min,range.max,label);
            }else if(property.propertyType == SerializedPropertyType.Integer)
            {
                Debug.Log("Integer类型");
                if (range.label != string.Empty) 
                {
                    label.text = range.label;
                }
    
                EditorGUI.IntSlider(position, property, (int)range.min, (int)range.max, label);
            }
    
        }
    }

    组件:

    using UnityEngine;
    using System.Collections;
    
    public class MyCompoment : MonoBehaviour {
    
        [MyRangeAttribute(0,10,"血值")]
        public int int1;
        public string string1;
    
    
    }

    项目资源图:

    image

    如果你感兴趣,你可以把你妹妹介绍给我
  • 相关阅读:
    Maven
    Maven
    Maven
    Maven
    Maven
    Maven
    Maven
    Python
    Maven
    include和require的区别
  • 原文地址:https://www.cnblogs.com/plateFace/p/4324937.html
Copyright © 2020-2023  润新知