Unity Inspector 精灵图预览
为 Unity 中的 Sprite 类型属性提供了增强版的 Inspector 显示,在保留标准精灵选择功能的基础上,添加了大型预览图和精灵名称显示功能
代码
using UnityEngine;
using UnityEditor;// 1️⃣ 告诉 Unity:所有 Sprite 字段都用我来画
[CustomPropertyDrawer(typeof(Sprite))]
public class SpritePropertyDrawer : PropertyDrawer
{/* --------------------------------------------------* 1. 告诉 Unity 这一行有多高* -------------------------------------------------- */public override float GetPropertyHeight(SerializedProperty property, GUIContent label){// 我们给 100*100 的预览 + 一点留白,共 110 像素return 110f;}/* --------------------------------------------------* 2. 真正绘制 GUI* -------------------------------------------------- */public override void OnGUI(Rect position,SerializedProperty property, GUIContent label){// 让 Unity 帮我们处理 disable / prefab overridelabel = EditorGUI.BeginProperty(position, label, property);// 画左侧字段名,并返回剩余矩形区域position = EditorGUI.PrefixLabel(position,GUIUtility.GetControlID(FocusType.Passive), label);/* ---------- 1. 100×100 预览图 ---------- */Rect previewRect = new Rect(position.x,position.y,100f,100f);// ObjectField 既能显示又能拖拽赋值EditorGUI.ObjectField(previewRect,property,typeof(Sprite),GUIContent.none // 不显示额外文字);/* ---------- 2. 右侧显示精灵名称 ---------- */if (property.objectReferenceValue != null) // 有图才显示{Rect nameRect = new Rect(position.x + 105f, // 贴在预览图右侧position.y + 35f, // 垂直居中position.width - 105f, // 占满剩余宽度position.height);// 直接取资源名称EditorGUI.LabelField(nameRect,property.objectReferenceValue.name);}EditorGUI.EndProperty(); // 收尾}
}
效果图