module-inspector/Editor/Handles/SphereHandleAttributeDrawer.cs

72 lines
2.9 KiB
C#

using Module.Inspector.Editor.Utilities;
using UnityEditor;
using UnityEngine;
namespace Module.Inspector.Editor
{
[CustomPropertyDrawer(typeof(SphereHandleAttribute))]
internal sealed class SphereHandleAttributeDrawer : HandlePropertyDrawer
{
public override void Draw(HandleDrawerPropertyAttribute attribute, SerializedProperty serializedProperty)
{
var att = (SphereHandleAttribute)attribute;
bool hasPositionField = EditorHandleUtility.TryGetWorldPosition(serializedProperty, att.fieldPosition, att.space, out Vector3 worldPosition);
bool hasRotationField = EditorHandleUtility.TryGetWorldRotation(serializedProperty, att.fieldRotation, att.space, out Quaternion worldRotation);
float size = GetValue(serializedProperty);
Color color = Handles.color;
if (hasPositionField)
worldPosition = EditorHandleUtility.PositionHandle(worldPosition, worldRotation);
if (hasRotationField)
worldRotation = EditorHandleUtility.RotationHandle(worldPosition, worldRotation);
size = EditorHandleUtility.SphereHandle(worldPosition, worldRotation, size);
if (hasPositionField)
EditorHandleUtility.SetWorldPosition(serializedProperty, att.fieldPosition, worldPosition, att.space);
if (hasRotationField)
EditorHandleUtility.SetWorldRotation(serializedProperty, att.fieldRotation, worldRotation, att.space);
SetValue(serializedProperty, size);
Handles.color = color;
}
private float GetValue(SerializedProperty serializedProperty)
{
switch (serializedProperty.propertyType)
{
case SerializedPropertyType.Integer:
return serializedProperty.intValue;
case SerializedPropertyType.Float:
return serializedProperty.floatValue;
default:
return 1f;
}
}
private void SetValue(SerializedProperty serializedProperty, float value)
{
switch (serializedProperty.propertyType)
{
case SerializedPropertyType.Integer:
serializedProperty.intValue = Mathf.RoundToInt(value);
break;
case SerializedPropertyType.Float:
serializedProperty.floatValue = value;
break;
}
}
public override bool IsValidFor(SerializedProperty serializedProperty)
{
switch (serializedProperty.propertyType)
{
case SerializedPropertyType.Integer:
case SerializedPropertyType.Float:
return true;
default:
return false;
}
}
}
}