unity 使用PropertyDrawer 在Inspector 面板上自定义字段的显示方式
使用PropertyAttribute自定义特性,然后使用PropertyDrawer特性为其创造在Inspector 面板上的GUI,从而实现自定义Inspector 面板显示的效果
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;// 1. 创建自定义属性
public class MyRangeAttribute : PropertyAttribute
{public float min, max;public MyRangeAttribute(float min, float max) { this.min = min; this.max = max; }
}// 2. 创建对应的 PropertyDrawer
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(MyRangeAttribute))]
public class MyRangeDrawer : UnityEditor.PropertyDrawer
{public override void OnGUI(Rect position, SerializedProperty property, GUIContent label){// 绘制背景EditorGUI.DrawRect(position, new Color(0.8f, 0.8f, 1f, 0.2f)); // 淡蓝色背景//控制颜色GUI.color = Color.red;MyRangeAttribute range = (MyRangeAttribute)attribute;property.floatValue = EditorGUI.Slider(position, label, property.floatValue, range.min, range.max);EditorGUI.LinkButton(position, "测试的按钮Button");}
}
#endif// 3. 使用方式
public class Demo : MonoBehaviour
{[MyRange(0, 100)]public float value;
}