module-inspector/Editor/Windows/EditorWindowStringToField.cs

105 lines
3.1 KiB
C#

using System;
using UnityEditor;
using UnityEngine;
namespace Module.Inspector.Editor
{
internal sealed class EditorWindowStringToField : EditorWindow
{
private string[] names;
private string[] descriptions;
private string filter = string.Empty;
private bool needFocus = true;
private Vector2 scrollPosition;
private GUIStyle style0;
private GUIStyle style1;
private SerializedProperty property;
public static void Open(Type type, SerializedProperty property)
{
var window = GetWindow<EditorWindowStringToField>();
window.titleContent = new GUIContent(type.Name);
window.names = EditorTypeUtility.GetFieldsAsStrings(type);
window.descriptions = EditorTypeUtility.GetFieldsAsDescriptions(type);
window.property = property;
window.ShowAuxWindow();
}
private void OnGUI()
{
if (!IsValid())
return;
CreateStyles();
EditorGUILayout.BeginVertical();
{
EditorGUILayout.BeginHorizontal();
{
GUILayout.Label("Search");
GUI.SetNextControlName("TextField_Filter");
filter = EditorGUILayout.TextField(filter, GUILayout.Width(128));
GUILayout.FlexibleSpace();
if (GUILayout.Button("Close"))
Close();
}
EditorGUILayout.EndHorizontal();
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
{
for (int i = 0, j = 0; i < descriptions.Length; i++)
{
if (!descriptions[i].Contains(filter))
continue;
j++;
if (!GUILayout.Button(descriptions[i], j % 2 == 0 ? style0 : style1))
continue;
property.stringValue = names[i];
property.serializedObject.ApplyModifiedProperties();
Close();
}
}
EditorGUILayout.EndScrollView();
}
EditorGUILayout.EndVertical();
if (needFocus)
{
needFocus = false;
GUI.FocusControl("TextField_Filter");
}
}
private bool IsValid()
{
return names != null;
}
private void CreateStyles()
{
if (style0 != null)
return;
style0 = new GUIStyle(GUI.skin.box)
{
stretchWidth = true,
alignment = TextAnchor.MiddleLeft,
richText = true
};
style1 = new GUIStyle(style0)
{
normal = { background = null }
};
}
}
}