Unity 创建自定义属性绘制器
简介:
Unity自带了一些属性绘制的特性 [Header] [Tooltip] [ContextMenu] [ContextMenuItem] [Space] … …
自定义:
如果我们需要自定义类似于Unity提供的特性,那就需要通过自己实现逻辑
实现案例:
通过标签,使自定义的字段由整数显示成为时间的形式(时分秒)
1.创建属性
public class TimeAttribute : PropertyAttribute
{
public readonly bool DisplayHours;
public TimeAttribute(bool displayHours = false)
{
DisplayHours = displayHours;
}
}
2.定义绘制器
[CustomPropertyDrawer(typeof(TimeAttribute))]
public class TimeDrawer : PropertyDrawer
{
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUI.GetPropertyHeight(property) * 2;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
if (property.propertyType == SerializedPropertyType.Integer)
{
property.intValue = EditorGUI.IntField(
new Rect(position.x, position.y, position.width, position.height / 2),
label, Mathf.Max(0, property.intValue));
EditorGUI.LabelField(
new Rect(position.x, position.y+position.height / 2,position.width, position.height / 2),
TimeConverter(property.intValue));
}
else
{
EditorGUI.HelpBox(position, "类型必须为Int", MessageType.Error);
}
}
private string TimeConverter(int num)
{
if (attribute is TimeAttribute time)
{
if (time.DisplayHours)
{
var hours = num / 3600;
var minutes = num % 3600 / 60;
var seconds = num % 60;
return $"{hours}:{minutes.ToString().PadLeft(2, '0')}:{seconds.ToString().PadLeft(2, '0')}";
}
else
{
var minutes = num % 3600 / 60;
var seconds = num % 60;
return $"{minutes.ToString().PadLeft(2, '0')}:{seconds.ToString().PadLeft(2, '0')}";
}
}
return string.Empty;
}
}
3.对脚本自定义
[CustomEditor(typeof(TimeTest))]
[CanEditMultipleObjects]
public class TimeInspectorEditor : Editor
{
private SerializedProperty _serializedA;
private SerializedProperty _serializedB;
private SerializedProperty _serializedC;
private void OnEnable()
{
_serializedA = serializedObject.FindProperty("a");
_serializedB = serializedObject.FindProperty("b");
_serializedC = serializedObject.FindProperty("c");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
GUILayout.BeginVertical("box");
{
EditorGUILayout.PropertyField(_serializedA);
EditorGUILayout.PropertyField(_serializedB);
EditorGUILayout.PropertyField(_serializedC);
}
GUILayout.EndVertical();
serializedObject.ApplyModifiedProperties();
}
}
4.测试脚本
public class TimeTest : MonoBehaviour
{
[Time] public int a = 3900;
[Time(true)] public int b = 9000;
[Time] public float c = 3900f;
}
5.实现效果
|