如果你曾经希望你显式的颜色字段不再难以编辑,那就把这个脚本放到一个名叫Editor的文件夹里任何地方就可以了。
using UnityEditor;
using UnityEngine;
namespace Editor
{
[CustomPropertyDrawer(typeof(Color))]
internal sealed class ColorPropertyDrawer : PropertyDrawer
{
private const float hexWidth = 80f;
private const float alphaWidth = 40f;
private const float padding = 6f;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// Setup:
label = EditorGUI.BeginProperty(position, label, property);
position = EditorGUI.PrefixLabel(position, label);
int indent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
EditorGUI.showMixedValue = property.hasMultipleDifferentValues;
// Colour:
EditorGUI.BeginChangeCheck();
float colourPickerWidth = (position.width - hexWidth - padding - alphaWidth - padding);
Color color = EditorGUI.ColorField(new Rect(position.x, position.y, colourPickerWidth, position.height), property.colorValue);
if (EditorGUI.EndChangeCheck() == true)
property.colorValue = color;
// Hex:
EditorGUI.BeginChangeCheck();
string hex = EditorGUI.DelayedTextField(new Rect(position.x + colourPickerWidth + padding, position.y, hexWidth, position.height), string.Format("#{0}", ColorUtility.ToHtmlStringRGBA(property.colorValue)));
if (EditorGUI.EndChangeCheck() == true)
property.colorValue = (ColorUtility.TryParseHtmlString((hex.StartsWith("#") == true) ? hex : hex.Insert(0, "#"), out Color result) == true ? result : property.colorValue);
// Alpha:
EditorGUI.BeginChangeCheck();
float alpha = EditorGUI.Slider(new Rect(position.x + colourPickerWidth + padding + hexWidth + padding, position.y, alphaWidth, position.height), property.colorValue.a, 0f, 1f);
if (EditorGUI.EndChangeCheck() == true)
property.colorValue = new Color(property.colorValue.r, property.colorValue.g, property.colorValue.b, alpha);
// Restore:
EditorGUI.indentLevel = indent;
EditorGUI.showMixedValue = false;
EditorGUI.EndProperty();
}
}
}
改进:
- 直接输入或粘贴(!)六位16进制颜色代码
- 快速调节透明度(特别适合用于UI)
- 默认行为依然存在
我有这个脚本的变体已久,觉得清理一下放上来看了。
评论 (0)