Framwork/Assets/Scripts/Base/MonoBehaviour/ConditionalFieldAttribute.cs

56 lines
1.9 KiB
C#

using UnityEngine;
using UnityEditor;
// 自定义属性
public class ConditionalFieldAttribute : PropertyAttribute
{
public string conditionalSourceField;
public ConditionalFieldAttribute(string conditionalSourceField)
{
this.conditionalSourceField = conditionalSourceField;
}
}
// 自定义属性绘制器
[CustomPropertyDrawer(typeof(ConditionalFieldAttribute))]
public class ConditionalFieldDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
ConditionalFieldAttribute condHAtt = (ConditionalFieldAttribute)attribute;
bool enabled = GetConditionalFieldValue(condHAtt.conditionalSourceField, property);
EditorGUI.BeginDisabledGroup(!enabled);
if (enabled)
{
EditorGUI.PropertyField(position, property, label, true);
}
EditorGUI.EndDisabledGroup();
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
ConditionalFieldAttribute condHAtt = (ConditionalFieldAttribute)attribute;
bool enabled = GetConditionalFieldValue(condHAtt.conditionalSourceField, property);
return enabled ? EditorGUI.GetPropertyHeight(property, label) : -EditorGUIUtility.standardVerticalSpacing;
}
private bool GetConditionalFieldValue(string conditionalFieldName, SerializedProperty property)
{
string propertyPath = property.propertyPath;
string conditionPath = propertyPath.Replace(property.name, conditionalFieldName);
SerializedProperty sourcePropertyValue = property.serializedObject.FindProperty(conditionPath);
if (sourcePropertyValue != null)
{
return sourcePropertyValue.boolValue;
}
else
{
Debug.LogWarning("Cannot find property with name: " + conditionalFieldName);
return true;
}
}
}