module-inspector/Editor/Drawers/StringToAnimationClipNameAttributeDrawer.cs

81 lines
2.8 KiB
C#

using System.Collections.Generic;
using Module.Inspector.Editor.Utilities;
using UnityEditor;
using UnityEngine;
namespace Module.Inspector.Editor
{
[CustomPropertyDrawer(typeof(StringToAnimationClipAttribute))]
internal sealed class StringToAnimationClipAttributeDrawer : DrawerPropertyDrawer
{
private readonly List<string> names = new List<string>();
private GUIContent[] contentArr;
public override bool Draw(Rect position, DrawerPropertyAttribute attribute, SerializedProperty property, GUIContent label, EditorPropertyUtility.Result result)
{
if (property.propertyType != SerializedPropertyType.String)
return false;
var att = (StringToAnimationClipAttribute)attribute;
SerializedProperty spSibling = property.GetRelativeProperty(att.animationFieldName);
if (spSibling == null)
return false;
FetchParameters(spSibling);
EditorGUI.BeginChangeCheck();
EditorGUI.BeginProperty(position, label, property);
{
int index = names.IndexOf(property.stringValue);
if (index < 0)
index = 0;
int newIndex = EditorGUI.Popup(position, label, index, contentArr);
property.stringValue = newIndex >= 1 ? names[newIndex] : string.Empty;
}
EditorGUI.EndProperty();
bool changed = EditorGUI.EndChangeCheck();
if (changed)
property.serializedObject.ApplyModifiedProperties();
return true;
}
public override string GetErrorMessage(SerializedProperty property)
{
if (property.propertyType != SerializedPropertyType.String)
return "Only supports strings";
var att = (StringToAnimationClipAttribute)attribute;
return $"Missing field: {att.animationFieldName}";
}
private void FetchParameters(SerializedProperty property)
{
var animation = property.objectReferenceValue as Animation;
names.Clear();
names.Add("----");
if (animation != null)
{
AnimationClip[] clips = AnimationUtility.GetAnimationClips(animation.gameObject);
for (var i = 0; i < clips.Length; i++)
{
if (clips[i] != null)
names.Add(clips[i].name);
}
}
contentArr = new GUIContent[names.Count];
for (var i = 0; i < contentArr.Length; i++)
{
contentArr[i] = new GUIContent(names[i]);
}
}
}
}