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(); // 收尾}
}
效果圖