UI相关优化补充
This commit is contained in:
58
Assets/_Game/Scripts/Editor/Inspector/RequiredFieldDrawer.cs
Normal file
58
Assets/_Game/Scripts/Editor/Inspector/RequiredFieldDrawer.cs
Normal file
@@ -0,0 +1,58 @@
|
||||
using UnityEditor;
|
||||
using UnityEngine;
|
||||
using BaseGames.Core;
|
||||
|
||||
namespace BaseGames.Editor.Inspector
|
||||
{
|
||||
/// <summary>
|
||||
/// [RequiredField] 的 Inspector 绘制:未赋值时显示红色 HelpBox。
|
||||
/// </summary>
|
||||
[CustomPropertyDrawer(typeof(RequiredFieldAttribute))]
|
||||
public class RequiredFieldDrawer : PropertyDrawer
|
||||
{
|
||||
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
|
||||
{
|
||||
bool missing = IsMissing(property);
|
||||
if (missing)
|
||||
{
|
||||
var msgHeight = EditorGUIUtility.singleLineHeight * 1.6f;
|
||||
var msgRect = new Rect(position.x, position.y, position.width, msgHeight);
|
||||
var attr = (RequiredFieldAttribute)attribute;
|
||||
var hint = string.IsNullOrEmpty(attr.Hint) ? "" : $" ({attr.Hint})";
|
||||
EditorGUI.HelpBox(msgRect, $"必填字段未赋值{hint}", MessageType.Error);
|
||||
|
||||
var fieldRect = new Rect(position.x, position.y + msgHeight + 2, position.width,
|
||||
EditorGUIUtility.singleLineHeight);
|
||||
var prev = GUI.color; GUI.color = new Color(1f, 0.6f, 0.6f);
|
||||
EditorGUI.PropertyField(fieldRect, property, label);
|
||||
GUI.color = prev;
|
||||
}
|
||||
else
|
||||
{
|
||||
EditorGUI.PropertyField(position, property, label, true);
|
||||
}
|
||||
}
|
||||
|
||||
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
|
||||
{
|
||||
bool missing = IsMissing(property);
|
||||
float baseH = EditorGUI.GetPropertyHeight(property, label, true);
|
||||
return missing ? baseH + EditorGUIUtility.singleLineHeight * 1.6f + 4f : baseH;
|
||||
}
|
||||
|
||||
private static bool IsMissing(SerializedProperty p)
|
||||
{
|
||||
switch (p.propertyType)
|
||||
{
|
||||
case SerializedPropertyType.ObjectReference:
|
||||
return p.objectReferenceValue == null;
|
||||
case SerializedPropertyType.String:
|
||||
return string.IsNullOrEmpty(p.stringValue);
|
||||
case SerializedPropertyType.ExposedReference:
|
||||
return p.exposedReferenceValue == null;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 7fbd662bb1183a549b6b2c63b8fd86f6
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
Reference in New Issue
Block a user